How to use JSON with Jquery?

前端 未结 3 1702
盖世英雄少女心
盖世英雄少女心 2020-12-06 07:39

I\'m working at an app which would make a POST ajax request to a PHP script on my server. The script would query the database and return a row of records, as an array. (One

相关标签:
3条回答
  • 2020-12-06 08:00

    You can return the JSON encoded string to the JS by echoing it with a Content-Type of application/json.

    See above answer for the rest.

    0 讨论(0)
  • 2020-12-06 08:04

    To get JSON with jQuery, just use jQuery.getJSON(). Alternatively, you can use any other AJAX tool and then just eval() the json to get a javascript object.

    To loop through an array, I usually use jQuery.each():

    var recordList = yourMethodToGetRecordListWithAjax();
    
    jQuery.each(recordList, function()
    {
        alert(this.Name); // For example
    });
    
    0 讨论(0)
  • 2020-12-06 08:05

    1) in the php script:

    $return["foo"]  = "bar";
    $return["blah"] = "bleg";
    print json_encode($return);
    

    2) in the javascript:

    $.ajax({
      type: "POST",
      url: URL,
      cache: false,
      data: values,
      dataType: 'json',
      success: function(json) {
        var foo = json.foo;
        if (json.blah == "bleg") {
          // do stuff 
        }
      } // end success function
    }); // end ajax call
    
    0 讨论(0)
提交回复
热议问题