jQuery ajax request with json response, how to?

后端 未结 5 969
一向
一向 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:35

    Firstly, it will help if you set the headers of your PHP to serve JSON:

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

    Secondly, it will help to adjust your ajax call:

    $.ajax({
        url: "main.php",
        type: "POST",
        dataType: "json",
        data: {"action": "loadall", "id": id},
        success: function(data){
            console.log(data);
        },
        error: function(error){
             console.log("Error:");
             console.log(error);
        }
    });
    

    If successful, the response you receieve should be picked up as true JSON and an object should be logged to console.

    NOTE: If you want to pick up pure html, you might want to consider using another method to JSON, but I personally recommend using JSON and rendering it into html using templates (such as Handlebars js).

提交回复
热议问题