如何使用jQuery的AJAX和PHP数组复出之作数组、之作、如何使用、AJAX

由网友(我有一颗坚定不移的心)分享简介:我有这样一个jquery ajax请求; I have a jquery ajax request like;$.ajax({type: 'POST',url: 'processor.php',data: 'data1=testdata1&data2=testdata2&data3=testdata3',cache...

我有这样一个jquery ajax请求;

I have a jquery ajax request like;

$.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 设置为返回数组等等;

The handler processor.php is set to return an array like;

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

我想这样做在此基础上的客户端操作。如果说阵列[0]为'B',我想提醒喜。同样地,如果数组[2]是'X',我想提醒你好,等等。我如何过滤数组中的元素,以抓住他们的数据?

I want to do action in client side based on this. Say if array[0] is 'b', I want to alert "hi". Again if array[2] is 'x', I want to alert "hello", and so on. How can I filter array elements in order to grab their data?

推荐答案

您将不得不返回数组EN codeD在JSON形式类似以下

You will have to return the array encoded in the json form like following

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

那么你就可以访问它的JavaScript将其转换回数组/对象像

then you can access it in javascript converting it back to an array/object like

var result = eval(retuned_value);

您也可以通过所有的数组元素使用导航for循环

You can also navigate through all array elements using a for loop

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

在你的code就应该是这个样子:

in your code it should look something like:

$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");
      }
    }
});
阅读全文

相关推荐

最新文章