我想发布以下数据:
{
"contactsync":
{ "rev":4,
"contacts":[
{ "fields": [
{
"value":
{
"givenName":"dfgheeej",
"familyName":"ffftestfff"
},
"type":"name",
"flags":[],
"op":"add"
},
{
"value":"fffffff",
"type":"nickname",
"flags":[],
"op":"add"
},
{
"value":"fffff@fffff.com",
"type":"email",
"flags":[],
"op":"add"
}
],
"categories":[],
"op":"add"
}
}
}
到网址。 (例如:site.com/anything/add?format=json&wssid=t4764.444&wssid=some_value&windowid=&r=776566756)
如何通过可能的javascript将上述数据发布到网址? (我想为它创建一个包含脚本的html文件。)
这一切都不会发生在同一台服务器上,我想将数据从其他服务器发布到其他服务器上。
答案 0 :(得分:0)
如果脚本位于同一服务器上,服务器支持CORS或服务器支持JSONP,则可以使用ajax。使用jQuery将是:
var data = {"contactsync":{"rev":4,"contacts":[{"fields":[{"value":{"givenName":"dfgheeej","familyName":"ffftestfff"},"type":"name","flags":[],"op":"add"},{"value":"fffffff","type":"nickname","flags":[],"op":"add"},{"value":"fffff@fffff.com","type":"email","flags":[],"op":"add"}],"categories":[],"op":"add"}]}};
var url = 'site.com/anything/addformat=json&wssid=t4764.444&wssid=some_value&windowid=&r=776566756';
$.post(url, JSON.stringify(data), function(response) {
});
如果你不能使用ajax,你需要在php中创建一个代理(只需将json传递给远程地址并打印响应),如:
function post($url, $data) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
return curl_exec($ch);
}
function get_raw_post_data() {
if (isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
return $GLOBALS['HTTP_RAW_POST_DATA'];
} else {
return file_get_contents('php://input');
}
}
$url = "site.com/anything/addformat=json&wssid=t4764.444&wssid=some_value&windowid=&r=776566756";
echo post($url, get_raw_post_data());
然后在远程站点的url内部,你在同一台服务器上使用你的脚本。