0

我通过 Ajax 使用 PHP 返回一个客户地址数组(作为地址返回)。我 document.write 完美显示数组的addresses.responseText

Array ( [0] => Array ( [addressID] => 15804 [customerID] => 10 [loanID] => [address1] => 6 Road [address2] => [address3] => [town] => Their Town [county] => Their County [postCode] => Their postCode [reason] => [current] => 1 [timestamp] => 2013-03-13 14:41:39 ) [1] => Array ( [addressID] => 10 [customerID] => 10 [loanID] => [address1] => 21A Road [address2] => [address3] => [town] => Their 2nd Town [county] => Their 2nd County [postCode] => Their 2nd postCode [reason] => [current] => 0 [timestamp] => 2013-03-13 14:41:39 ) )

我在循环和使用数组信息时遇到了问题。

new Ajax.Request('includes/ajax.php',
        {
            method:'post',
            parameters: {addCustID: customerID},
            onSuccess: function(addresses){

            document.write(addresses.responseText);

                for (var i in addresses)
                {

                    if(i == "responseText") 
                    {                           
                        addressExpander.addEntry(addresses[i]);
                    }
                }
            },
            onFailure: function(){ alert('Something went wrong...') }
        });

我想addressExpander.addEntry(addresses[i]);为每个地址运行,但它只显示一次,而不是每个地址。

我试过在循环addresses.responseTextif(i == "responseText")循环,但它什么也没做。

顺便说一句,我正在使用 Prototype,它已经在页面中使用。

4

2 回答 2

0

您遇到的问题似乎是PHP 数组Javascript 数组之间存在相当大的差异。

为了帮助弥补这些差异,我们的霸主创建了全能的 JSON 格式,这有助于实现跨语言数据结构的共享。在回显您的 PHP 响应之前,请像这样使用json_encode :

echo json_encode($your_php_arr);

您的 JS 代码应该能够在不进行任何修改的情况下工作。如果没有,请尝试JSON.parse在 onSuccess 回调中添加一个:

var your_js_arr = JSON.parse(addresses.responseText);

for (var i in your_js_arr)
{               
    addressExpander.addEntry(your_js_arr[i]);
}
于 2013-08-20T14:52:29.377 回答
0

假设这条线:

document.write(addresses.responseText);

是产生您发布的输出的那个,您正在打印出addresses.responseText,它是地址数组。

正如您在回答中所说,从外观上看,您需要遍历addresses.responseText:

for (var i=0;i<addresses.responseText.length;i++)
{     
     addressExpander.addEntry(addresses.responseText[i]);
}
于 2013-08-20T14:53:14.027 回答