简体   繁体   English

如何解码从php到jquery ajax的数组响应?

[英]How to decode array response from php to jquery ajax?

I have PHP function: 我有PHP功能:

public function doit()
{
    $arr1= array();
        $arr1['index1'] = 'value1';
            $arr1['index2'] = 'value2';
}

I call it from my JQuery function: 我从我的JQuery函数中调用它:

$.ajax
({    
    url: "/controller/doit",  
    success: function()
    { 
        alert('done!'); 
    }  
 });  

Everything I want is - that my JQuery function, which contains this ajax call will return me the array, which is identical to the one, which PHP function returned (the only difference is language of course: JS instead of PHP) 我想要的一切 - 我的JQuery函数,包含这个ajax调用将返回我的数组,这与PHP函数返回的数组相同(当然唯一的区别是语言:JS而不是PHP)

You need to return something from your doit function. 你需要从你的doit函数返回一些东西。

public function doit()
{
  $arr1= array();
  $arr1['index1'] = 'value1';
  $arr1['index2'] = 'value2';

  echo json_encode($arr1);
}


$.ajax
({    
  url: "/controller/doit",  
  success: function(data)
  { 
    console.log(data); 
  }  
});  

Edit: 编辑:

Jquery to PHP: When the javascript is run, it will send the data array to the server using the url. Jquery to PHP:当javascript运行时,它会使用url将数据数组发送到服务器。 The server receives the array, encodes it as json and sends it back to the success callback function which will log the data to the console. 服务器接收数组,将其编码为json并将其发送回成功回调函数,该函数将数据记录到控制台。

// YOUR JAVASCRIPT FILE
// your data to send.
var data = {'index1': 'value1', 'index2': 'value2'};

$.ajax({
  type: 'POST',
  url: '/controller/doit',
  data: data,
  success: function(data) { console.log(data) },
  dataType: 'json'
});


//YOUR PHP FILE
public function doit()
{ 
   // you should be setting your content type header to application/json if sending json
   header('Content-type: application/json');
   echo json_encode($_POST['data']);
}

You can echo the array as json from php using: 您可以使用以下命令将数组作为json从php回显:

echo json_encode($arr1);

And use $.getJSON in your JS: 并在JS中使用$ .getJSON:

$.getJSON('/controller/doit', function(data) {
  console.log(data);
});

you can use JSON to encode your array. 您可以使用JSON对数组进行编码。 http://php.net/manual/en/function.json-encode.php http://php.net/manual/en/function.json-encode.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM