我正在尝试使用代理脚本发送帖子数据以执行跨域 ajax。
var data = "url=http://www.fhm.com.ph/templates/100sexiestwomen2013/ajax/set.php&id=13&index=0&action=add";
$.ajax({
url: "proxy.php",
data: data,
type: "POST",
success: function(data, textStatus, jqXHR) {
console.log('Success ' + data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error ' + jqXHR);
}
});
然后我尝试解析数据以用作代理脚本中的 url 和参数。
<?php
//set POST variables
$url = $_POST['url'];
unset($_POST['url']);
$fields_string = "";
//url-ify the data for the POST
foreach($_POST as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
$fields_string = rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
但事实证明它没有正确发布数据。
尝试使用邮递员,一个 chrome 扩展POSTMAN。并给出正确的键值对,如data
.
它会null
在第一次提交和selected
第二次提交时为您提供。
我错过了什么。
编辑
<?php
//set POST variables
$url = $_POST['url'];
// unset($_POST['url']);
// $fields_string = "";
// //url-ify the data for the POST
// foreach($_POST as $key=>$value) {
// $fields_string .= $key.'='.$value.'&';
// }
// $fields_string = rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$_POST);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
如编辑所示,我删除了手动构建,而是使用了 POST 数组。