我想使用javascript对外部网址执行POST请求。 目前我使用php服务器端发送请求
$data = array(
'TokenExID' => $tokenex_id,
'APIKey' => $api_key,
'EcryptedData' => $encrypted_data,
'TokenScheme' => 4
);
$ch = curl_init("https://api.testone.com/TokenServices.svc/REST/TokenizeFromEncryptedValue");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json', //
'Accept: application/json') //
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
我想在javascript中使用相同的代码。
var url =" https://api.testone.com/TokenServices.svc/REST/TokenizeFromEncryptedValue&#34 ;;
var params = "abcd";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
我得到了这个javascript示例代码,但我不知道怎么做。我是javascript的新手,但无法找到办法做到这一点。可以帮我一个人吗?
答案 0 :(得分:3)
如果您是javascript的新手,我强烈建议您使用jQuery,这将大大减轻您的工作量。在线搜索如何将其包含在您的页面中,然后这是代码。
var data = {
param1: "value1",
param2: "value2"
// add here more params id needed followinf the same model
};
$.ajax({
type: "POST",
url: 'http://www.myrestserver.com/api',
data: data,
success: success
});
function success(result) {
// do something here if the call is successful
alert(result);
}
https://api.jquery.com/jQuery.ajax/
如果您想进一步检查:JavaScript post request like a form submit
希望它有所帮助, 保罗