jQuery ajax request with json response, how to?

后端 未结 5 955
一向
一向 2020-11-27 19:08

I am sending an ajax request with two post values, the first is "action" which defines what actions my php script has to parse, the other is "id" which i

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 19:33

    You need to call the

    $.parseJSON();
    

    For example:

    ...
    success: function(data){
           var json = $.parseJSON(data); // create an object with the key of the array
           alert(json.html); // where html is the key of array that you want, $response['html'] = "something..";
        },
        error: function(data){
           var json = $.parseJSON(data);
           alert(json.error);
        } ...
    

    see this in http://api.jquery.com/jQuery.parseJSON/

    if you still have the problem of slashes: search for security.magicquotes.disabling.php or: function.stripslashes.php

    Note:

    This answer here is for those who try to use $.ajax with the dataType property set to json and even that got the wrong response type. Defining the header('Content-type: application/json'); in the server may correct the problem, but if you are returning text/html or any other type, the $.ajax method should convert it to json. I make a test with older versions of jQuery and only after version 1.4.4 the $.ajax force to convert any content-type to the dataType passed. So if you have this problem, try to update your jQuery version.

提交回复
热议问题