我正在使用google地图API进行一些距离计算,并希望将一个数组从JS传递到一个完全不同的PHP页面。我认为这样做是正确的:在页面output.php上使用JS将json字符串输出到html主体,然后在另一个页面上使用cURL输出php页面(retrieve.php)以获取页面内容。但这将检索HTML页面的全部内容,包括javascript、html标记等。我只希望能够从JS生成的页面中检索json字符串,并在不同的页面上使用PHP中的此json。做这件事最好的方法是什么?
谢谢
尝试输出json的js代码:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
<script type="text/javascript">
window.onload = function() {
var myObj = {
1: 1,
2: 2,
3: 4,
4: 3
};
document.body.innerHTML = JSON.stringify(myObj);
}
</script>
</head>
<body>
</body>
</html>
PHP文件:
$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,'http://localhost:81/output.php');
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json')
);
$content = curl_exec($curl_handle);
curl_close($curl_handle);
$array = json_decode($content);
print_r($array);
发布于 2014-07-15 18:55:13
在客户机上运行的JavaScript将不能以不同的页面请求能够读取的方式将数据输出到页面。它只能修改页面的内存副本。
将数据序列化为查询字符串,并通过location = other_php_url + query_string
转到另一个PHP页面,然后从$_GET
读取数据,而不是使用cURL
。
发布于 2014-07-15 18:55:27
尝试使用ajax调用,如下所示(这是使用jQuery):
my_json_data = {"my_data": "blabla"};
$.ajax({
url: 'http://www.mywebsite.com/my_php_script.php',
type: "POST",
data: my_json_data,
success:function(data){
alert("Data received");
}
});
在php端,你应该这样做:
<?php //This is my_php_script.php
$my_data = $_POST["my_data"];
...
https://stackoverflow.com/questions/24756230
复制相似问题