Creating JSON data using PHP and parsing it using jQuery

前端 未结 3 449
醉梦人生
醉梦人生 2020-12-21 12:45

I am using a PHP script to create JSON data. It looks like this:

{\"Id\":0}

Now if I put that into a file and then load it using ajax it\'s

相关标签:
3条回答
  • 2020-12-21 13:05

    Doctypes belong on HTML documents, not JSON.

    Try something like this in your PHP file (and only this)

    <?php
    header('Content-Type: application/json');
    ?>
    {"Id":0}
    

    Given what you have posted, I can't see any reason to even involve PHP. I'm guessing you've only posted a very simple example. Should it become more complex, involving server-side processing, data retrieval, etc, use PHP's json_encode(), for example

    <?php
    header('Content-Type: application/json');
    $data = array(
        'Id'  => 0,
        'foo' => $someOtherComplexVariable
    );
    echo json_encode($data);
    exit;
    
    0 讨论(0)
  • 2020-12-21 13:09

    use jquery's parseJSON
    e.g.

    success: function(data) {
        data = jQuery.parseJSON(data);
     $('#result').html('#Id=' + data.Id);
    }
    
    0 讨论(0)
  • 2020-12-21 13:13

    In your error function use this and check what data is being returned from the server.

    error: function(jqXHR, textStatus, errorThrown) {
       $('#result').html(textStatus + ' | ' + errorThrown + ' | ' + jqXHR.responseText);
       alert(jqXHR.responseText);
    }
    

    You will know where exactly it is going wrong. The data type and the special characters. Set the content type to application/json and encode your json string using json_encode(). Also, you don't need the doctypes.

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