Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用curl和ajax发送post数据_Php_Ajax_Json_Proxy_Cross Domain - Fatal编程技术网

Php 使用curl和ajax发送post数据

Php 使用curl和ajax发送post数据,php,ajax,json,proxy,cross-domain,Php,Ajax,Json,Proxy,Cross Domain,我正在尝试使用代理脚本发送post数据,以执行跨域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, textSta

我正在尝试使用代理脚本发送post数据,以执行跨域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);

如编辑中所示,我删除了手动构建,而是使用了POST数组。

您必须正确编码数据

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

因为url参数包含在url中具有特殊含义的字符

将Javascript中的对象用于
数据
,以便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将正确编码。

@Joey Salachipolito好的,我现在知道发生了什么,我认为它只是一个参数。我认为它仍然不起作用,你也可以试试,也许我会摆弄它,想摆弄它吗?@Joey Salachipolito尝试设置
curl\u setopt($ch,CURLOPT\u POSTFIELDS,$\u POST)
使用
$\u POST
而不是手动尝试构建帖子正文。我将发布您的建议,但它似乎不起作用。
curl_setopt($ch,CURLOPT_POSTFIELDS,$_POST);