I am trying to send json with ajax to php file for that I have tried below code

我正在尝试将带有ajax的json发送到php文件,因为我尝试了下面的代码

  1. 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 echoing 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);

更多相关文章

  1. php mail函数一段好的代码
  2. 用于上传多个文件的PHP代码
  3. (phpQuery)对网站产品信息采集代码的优化
  4. 韩顺平_php从入门到精通_视频教程_学习笔记_源代码图解_PPT文档
  5. 【MySQL 技巧分享】 mysql -e 加 v 简化代码
  6. Oracle相当于MySQL代码“插入虚拟”以返回错误消息
  7. 登录使用PHP并´t显示任何html代码
  8. 在代码点火器中从mysql迁移到postgresql
  9. 【动软.Net代码生成器】连接MySQL生成C#的POCO实体类(Model)

随机推荐

  1. Android EditText 代码实现键盘弹出打开
  2. android 整合 maven 环境
  3. 有关谷歌Android和Java历史的一课
  4. Android JUnit单元测试
  5. Android数据库操作的两种方式
  6. android 中限制EditText 最大输入字符数
  7. Google Maps API Key申请方法及地址
  8. Android解析自定义xml文件--Sax解析xml文
  9. Android中的存储路径之外部存储
  10. android studio 3.6.0 绑定视图新特性