使用json数据跨域发布请求

时间:2016-03-31 13:37:42

标签: json ajax post cross-domain httprequest

我已经阅读了两天的教程,我真的不明白我的选择是什么。我有一台运行Web服务器的HMI机器(我不知道是什么类型的Web服务器)。我可以使用json数据访问POST请求的HMI标签值。 rquest示例看起来像这样

int f(int a[], int size) {
    if (size == 1)
        return arr[0];
    size--;
    return f((arr + (arr[0] > a[size])), size);
}

响应是json数据。

问题当然是跨域政策。我无法控制机器,也没有设置CORS的选项。我已经阅读了有关代理,iframe和yql解决方案,但据我所知,我无法通过这些变通方法发送json数据。有没有办法如何用json跨域发送帖子请求?

谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我正在使用php curl发送请求。

以下是工作代码:

$data = array("getTags" => array("Var1","Var2"), "includeTagMetadata" => false);                                                                    
$data_string = json_encode($data);
$agent= 'Mozilla/5.0 (Windows; U;Windows NT 5.1; ru; rv:1.8.0.9) Gecko/20061206 Firefox/1.5.0.9';
//open connection
$ch = curl_init();
$f = fopen('request.txt', 'w'); //writes headers to this file
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,"domainipaddress");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($ch,CURLOPT_POSTFIELDS,$data_string);
$tmpfname = dirname(__FILE__).'/cookie.txt'; //saves the cookie from server
curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfname);
curl_setopt($ch, CURLOPT_COOKIEFILE, $tmpfname);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch,  CURLOPT_VERBOSE,  1 ); 
curl_setopt( $ch,  CURLOPT_STDERR,  $f );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_FORBID_REUSE, false);                                                                    
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                        
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string),
       'Connection: keep-alive',
       "Keep-Alive: 300"
    )                                                                       
);  

//execute post
$result = curl_exec($ch);
$headers = curl_getinfo($ch);
fclose($f);