jQuery工作在JSON中


jQuery work in JSON

我想通过AJAX将数据从index.php发送到浏览器。我想把它编码成JSON并解码它来处理它。我用的是jQuery.ajax()。你能给我指个教程吗?

假设您的ajax调用看起来像这样

$.ajax({
   ....
   .....
   dataType: 'json', // required
   success: function(data) { // data variable is where your json is stored
       console.log(data); // view entire json object in firebug or other console
       alert(data.name); // access value of array key called name 
   }
});

我建议在成功函数中放置一个console.log调用,看看json对象是什么样子的

在index.php中放入jquery代码

$.post("data_provider.php",{'your_param': param_value},
     function(data){
     var jsonObj = JSON.parse(data);
      //use your data here 
     jsonObj.id;
     jsonObj.name; 
});

在您的data_provider.php中,例如,从DB获取数据并使用json_encode函数对它们进行编码。例如:

$your_data = array('id' => $id, 'name' => $name );
echo json_encode ($your_data);

在ajax调用中,您可以根据需要使用get或post。