使用ajax在服务器端恢复json时出错
I am trying to send json with ajax to php file for that I have tried below code
我正在尝试将带有ajax的json发送到php文件,因为我尝试了下面的代码
Using jquery
使用jquery
var dummyData = {'bob': 'foo', 'paul': 'dog'}; var ajaxRequest = $.ajax({ url: "json_handler.php", type: "POST", contentType: "application/json; charset=utf-8", data: JSON.stringify(dummyData ), dataType: "json" }); ajaxRequest.done(function (response, textStatus, jqXHR) { console.log(response + textStatus + jqXHR); alert('sd'); }); ajaxRequest.fail(function (e) { console.log(e); });
And i am just doing var_dump($_REQUEST)
at json_handler.php
and ajax request is keep failing and get nothing in response text
我只是在json_handler.php上做var_dump($ _ REQUEST)而ajax请求一直在失败并且在响应文本中什么都没有
When i tried
我试过的时候
$json = file_get_contents('php://input');
var_dump($json);
I got the json but ajax request is still failing.
我得到了json但ajax请求仍然失败。
I have also tried to do this javascript and my code is below
我也尝试过这个javascript,我的代码如下
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = stateHandler;
httpRequest.open("POST", "json_handler.php", true);
httpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
httpRequest.send( JSON.stringify(dummyData ));
Here is my console log
这是我的控制台日志
2 个解决方案
#1
4
See because your ajax is having dataType: "json"
so it is expecting the response in json
format which is like {key:value} or [{k:v}, {k:v}, ....]
and you are not echo
ing any json structure so this is where your ajax is failing.
看看因为你的ajax有dataType:“json”所以它期待json格式的响应,就像{key:value}或[{k:v},{k:v},....]而你是不回显任何json结构,所以这是你的ajax失败的地方。
Seems to me you have to write it this way:
在我看来你必须这样写:
$json = file_get_contents('php://input');
echo json_encode($json);
更多相关文章
- php mail函数一段好的代码
- 用于上传多个文件的PHP代码
- (phpQuery)对网站产品信息采集代码的优化
- 韩顺平_php从入门到精通_视频教程_学习笔记_源代码图解_PPT文档
- 【MySQL 技巧分享】 mysql -e 加 v 简化代码
- Oracle相当于MySQL代码“插入虚拟”以返回错误消息
- 登录使用PHP并´t显示任何html代码
- 在代码点火器中从mysql迁移到postgresql
- 【动软.Net代码生成器】连接MySQL生成C#的POCO实体类(Model)