如何使用jQuery AJAX和PHP数组返回进行工作

10

我有一个类似于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");
      }
    }
});

处理程序processor.php被设置为返回一个类似以下的数组;

$array = array("a","b","c","d");
echo $array;

我想在客户端执行基于此的操作。例如,如果array[0]是“b”,我想弹出“hi”。再比如,如果array[2]是“x”,我想弹出“hello”,以此类推。如何筛选数组元素以获取它们的数据?

5个回答

25
你需要将数组以以下json形式进行编码并返回。
$array = array("a","b","c","d");
echo json_encode($array);

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

var result = eval(retuned_value);

您也可以使用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]);
}

在你的代码中应该长这样:

PHP代码:

$array = array("a","b","c","d");
echo json_encode( $array );

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");
      }
    }
});

3
不需要使用eval - Ram
1
我用 eval 解决了问题,但没有使用 eval 就无法解决。此外,我的 PHP 脚本没有设置任何特定的标题,就像下面的答案中 HMR 所说的那样。 - Janaka R Rajapaksha

2
我发现将数组从php返回给Ajax(jscript)最好的方法是:
在php端:echo json_encode($myArray); 在javascript端(例如myAjax.responseText): replyVal = JSON.parse(myAjax.responseText); 要将数组从javascript发送到php,请使用匹配的JSON.stringify()进行发送,并使用php的json_decode()进行接收。

2

1
在您的PHP代码中,将数组编码为JSON对象。
echo json_encode($array);

然后您需要将JSON对象转换为JavaScript/jQuery兼容的对象。之后,您可以将其转换回数组。

$.ajax({
      success: function(result) {

      jq_json_obj = $.parseJSON(result); //Convert the JSON object to jQuery-compatible

      if(typeof jq_json_obj == 'object'){ //Test if variable is a [JSON] object
        jq_obj = eval (jq_json_obj); 

        //Convert back to an array
        jq_array = [];
        for(elem in jq_obj){
            jq_array.push(jq_obj[elem]);
        }
        console.log(jq_array);
      }else{
        console.log("Error occurred!"); 
      }
    }
});

-1
$.ajax({  
    type: 'POST',  
    url: 'processor.php',//please return in json  
    dataType : 'json',//to get data in json   
    data: 'data1=testdata1&data2=testdata2&data3=testdata3',  
    cache: false,  
    success: function(result) {  
      if(result.array.length > 0){  
        for(var i=0;i<result.array.length;i++){  
            if(result.array.[i]== 'a'){  
               //do somthing..  
               //here, you can use switch case too...  
            }  
        }  
      }  
    }  
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接