2012-12-29 52 views
0

我正在用php脚本抓取一个网站,并在最后创建一个数组,我想要发送回javascript调用方函数。在下面的代码中,我试图用'print_r'打印出来,它根本不给我任何结果(?)。如果我回显元素(例如$ addresses [1]),则显示该元素。从PHP发送数组到javascript

那么,为什么我没有从PHP函数中获取任何东西,以及将数组发送回调用js函数的最佳方法是什么?

非常感谢!

JS:

$.post( 
    "./php/foo.php", 
    { 
    zipcode: zipcode 
    }, 
    function(data) { 
    $('#showData').html(data); 
    } 
); 

PHP:

$tempAddresses = array(); 
$addresses = array(); 

$url = 'http://www.foo.com/addresses/result.jspv?pnr=' . $zipcode; 

$html = new simple_html_dom(); 
$html = file_get_html($url); 

foreach($html->find('table tr') as $row) { 
    $cell = $row->find('td', 0); 

    array_push($tempAddresses, $cell); 
} 

$tempAddresses = array_unique($tempAddresses); 

foreach ($tempAddresses as $address) { 
    array_push($addresses, $address); 
} 

print_r($addresses); 
+1

http://php.net/manual/en/function.json-encode.php – Prinzhorn

+0

尝试用回声json_encode( $地址); –

回答

4

您可以使用JSON将数组返回给客户端,它可以通过AJAX发送,与您在现有代码中执行的操作相同。

PHP的使用json_encode(),此功能将使您的PHP数组转换成JSON字符串,你可以使用它通过使用AJAX

在你的PHP代码发送回客户端(只是为了演示它的工作原理)

json.php

<?php 
$addresses['hello'] = NULL; 
$addresses['hello2'] = NULL; 
if($_POST['zipcode'] == '123'){ //your POST data is recieved in a common way 
    //sample array 
    $addresses['hello'] = 'hi'; 
    $addresses['hello2'] = 'konnichiwa'; 
} 
else{ 
    $addresses['hello'] = 'who are you?'; 
    $addresses['hello2'] = 'dare desu ka'; 
} 
echo json_encode($addresses); 
?> 

然后在您的客户端脚本(更好的使用jQuery的AJAX长路)

$.ajax({ 
    url:'http://localhost/json.php', 
    type:'post', 
    dataType:'json', 
    data:{ 
     zipcode: '123' //sample data to send to the server 
    }, 
    //the variable 'data' contains the response that can be manipulated in JS 
    success:function(data) { 
      console.log(data); //it would show the JSON array in your console 
      alert(data.hello); //will alert "hi" 
    } 
}); 

引用

http://api.jquery.com/jQuery.ajax/

http://php.net/manual/en/function.json-encode.php

http://json.org/

+0

谢谢。试了一下,但我只是空回到js功能:/ – holyredbeard

+0

我在我身边做了同样的事情,它工作正常。请仔细检查PHP代码。 –

+0

反正我怀疑你的网址,请确保根据你如何通过网络浏览器访问php文件来更正它 –

1

JS应该是

$.ajax({ 
    url:'your url', 
    type:'post', 
    dataType:'json', 
    success:function(data) { 
     console.log(JSON.stringify(data)); 
    } 
    }); 

服务器

$tempAddresses = array(); 
$addresses = array(); 

$url = 'http://www.foo.com/addresses/result.jspv?pnr=' . $zipcode; 

$html = new simple_html_dom(); 
$html = file_get_html($url); 

foreach($html->find('table tr') as $row) { 
    $cell = $row->find('td', 0); 

    array_push($tempAddresses, $cell); 
} 

$tempAddresses = array_unique($tempAddresses); 

foreach ($tempAddresses as $address) { 
    $arr_res[] =$address; 
} 
header('content-type:application/json'); 
echo json_encode($arr_res); 
+0

'JSON.parse'替代'JSON.stringify' –

+1

@fireeyedboy JSON.stringify它显示结果作为字符串在控制台,否则作为对象,只是为了如何数据来 –

+0

啊是的,我明白了。当然。 –