1

我正在尝试使用代理脚本发送帖子数据以执行跨域 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 数组。

4

2 回答 2

2

在 Javascript 中使用一个对象data,以便 jQuery 对其进行正确编码:

var data = {
   url: "http://www.fhm.com.ph/templates/100sexiestwomen2013/ajax/set.php&id=13",
   index: 0,
   action: "add"
};

在 PHP 中,使用数组CURLOPT_POSTFIELDS

curl_setopt($ch,CURLOPT_POSTFIELDS,$_POST);

PHP 会正确编码。

于 2013-04-16T07:04:27.033 回答
1

您必须正确编码您的数据

var data = "url=" + encodeURIComponent("http://www.fhm.com.ph/templates/100sexiestwomen2013/ajax/set.php")+"&id=13&index=0&action=add";

由于您的 url 参数包含在 url 中具有特殊含义的字符。

于 2013-04-16T07:00:18.143 回答