如何使用jQuery AJAX和PHP数组返回

bla*_*d Ψ 10 javascript php arrays ajax jquery

我有一个jquery ajax请求;

$.ajax({
    type: 'POST',
    url: 'processor.php',
    data: 'data1=testdata1&data2=testdata2&data3=testdata3',
    cache: false,
    success: function(result) {
      if(result){
        alert(result);
      }else{
        alert("error");
      }
    }
});
Run Code Online (Sandbox Code Playgroud)

处理程序processor.php设置为返回一个数组;

$array = array("a","b","c","d");
echo $array;
Run Code Online (Sandbox Code Playgroud)

我希望在此基础上在客户端采取行动.假设如果array [0]是'b',我想提醒"hi".再次,如果array [2]是'x',我想提醒"hello",依此类推.如何过滤数组元素以获取数据?

Abu*_*sae 24

您将必须返回以json形式编码的数组,如下所示

$array = array("a","b","c","d");
echo json_encode($array);
Run Code Online (Sandbox Code Playgroud)

然后你可以在javascript中访问它,将其转换回数组/对象

var result = eval(retuned_value);
Run Code Online (Sandbox Code Playgroud)

您还可以使用for循环遍历所有数组元素

for (var index in result){
    // you can show both index and value to know how the array is indexed in javascript (but it should be the same way it was in the php script)
    alert("index:" + index + "\n value" + result[index]);
}
Run Code Online (Sandbox Code Playgroud)

在你的代码中它应该看起来像:

PHP代码:

$array = array("a","b","c","d");
echo json_encode( $array );
Run Code Online (Sandbox Code Playgroud)

jQuery脚本

$.ajax({
    type: 'POST',
    url: 'processor.php',
    data: 'data1=testdata1&data2=testdata2&data3=testdata3',
    cache: false,
    success: function(result) {
      if(result){
        resultObj = eval (result);
        alert( resultObj );
      }else{
        alert("error");
      }
    }
});
Run Code Online (Sandbox Code Playgroud)

  • -1无需使用`eval`. (3认同)