Returning a JSON object from PHP in AJAX call?

前端 未结 3 513
旧巷少年郎
旧巷少年郎 2021-01-02 11:30

Here\'s my PHP code called during jQuery AJAX call:



        
相关标签:
3条回答
  • 2021-01-02 11:54

    The response you are getting from your PHP script is in plain text. You can however parse that string into an object using $.parseJSON in your callback function:

    $.ajax({
        url      : url,//note that this is setting the `url` property to the value of the `url` variable
        data     : {ID:$('#ddlClients').val()},
        type     : 'post',
        success  : function(Result){
                var myObj = $.parseJSON(Result);
                //you can now access data like this:
                //myObj.Address_1
            }
        }
      );
    

    You can let jQuery do this for you by setting the dataType property for your AJAX call to json:

    $.ajax({
        url      : url//note that this is setting the `url` property to the value of the `url` variable
        data     : {ID:$('#ddlClients').val()},
        dataType : 'json',
        type     : 'post',
        success  : function(Result){
                //you can now access data like this:
                //Result.Address_1
            }
        }
      );
    

    The above examples expect that the response from the server to be in this format (from your question):

    "{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road"}
    
    0 讨论(0)
  • 2021-01-02 11:59

    json_encode accepts objects, so there's no need to do that automatic array-building.:

    $row = $result->fetch_object();
    echo json_encode($row);
    

    It's as simple as that!

    0 讨论(0)
  • 2021-01-02 12:04

    In your $.post call, the last argument could be the data-type: json:

    $.post(url, {ID:$('#ddlClients').val()},
        function(Result){
            alert(Result.Address_1);
        },'json'
     );
    

    Everything should work then, as it looks like you are doing everything right.

    0 讨论(0)
提交回复
热议问题