简体   繁体   中英

Jquery ajax response error

Here is a partial example of what I am trying to achieve.

I am trying to retrieve a value from ajax but the javascript result.success variable is undefined. I have the following:

PHP:

$result = array ("success" => null, "html" => "");
$result['success'] = true;
$result['html'] = "test";
echo json_encode($result);

Javascript/jQuery:

var ID = 1
$.ajax({
            type: 'POST',
            url: '/ajax/load.php',
            contentType: "application/json; charset=utf-8",
            datatype: 'json',
            data: {ID: ID},
            beforeSend: function(xhrObj) {
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Accept","application/json");
            },
            success: function(result) {
                if (result.success) {
                        // do something
                }
        });

The response I am getting from ajax (retrieved from chrome dev tools) is {"success":true,"html":"Test"}

This looks fine to me however in the JavaScript result.success is undefined. I believe this will be simple I just can't see where the issue lies..

Your error is here:

datatype: 'json',

Javascript is case sensitive and the property is dataType :

dataType: 'json',

Because of that, jQuery is not being told to automatically parse the JSON, so the result is just treated as html or plain text.

You also need to remove the content-type header because that specifies the content type for the request not response. You are sending form/url encoded in the request, not JSON.

$.ajax({
            type: 'POST',
            url: '/ajax/load.php',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: {ID: ID},
            beforeSend: function(xhrObj) {
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Accept","application/json");
            },
            success: function(result) {
                if (result.success) {
                        // do something
                }
            } // Maybe your forgot this
        });

in other words - Basic Debugging

在您的PHP页面中,将其放在页面顶部(您仅接受json响应,但响应头的内容类型可能是text / html

header('Content-type: application/json');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM