[英]Perform POST request using JavaScript
我想使用javascript對外部URL執行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 ”;
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的新手,但無法找到辦法做到這一點。可以幫我一個人嗎?
如果你是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發布請求,如表單提交
希望它有所幫助,保羅
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.