我想使用 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 post request like a form submit
希望对你有帮助 保罗
关于javascript - 使用 JavaScript 执行 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22730561/