dougehe2022 2015-08-24 08:52
浏览 78
已采纳

使用ajax在服务器端接收json时出错

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

  1. Using 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

When i tried

$json = file_get_contents('php://input');
var_dump($json);

I got the json but ajax request is still failing.

I have also tried to do this javascript and my code is below

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

enter image description here

  • 写回答

2条回答 默认 最新

  • doz22551 2015-08-24 09:00
    关注

    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.

    Seems to me you have to write it this way:

    $json = file_get_contents('php://input');
    echo json_encode($json);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?