[英]How to send data in HTTP POST request while calling a url?
我寫了一個簡單的jsp頁面,在其中我的部門中加載了一個外部網站。
下面是代碼:
<html>
<head>
<script src="../common/jquery-1.6.2.min.js"></script>
<script>
$(document).ready(function(){
$("#menu").html('<object data="www.someurl.com">').appendTo('body');;
});
</script>
</head>
<body>
<div id="menu" style="position:relative; bottom: 0; overflow:hidden;">
</div>
</body>
</html>
基本上,我正在做的是,我正在設置HTML內容,該內容在object標記內具有src URL。 這是成功的,我可以在我的部門內加載Web URL。
當我想使用HTTP POST方法發送一些數據(可能是單個變量)時,問題就來了。
有什么方法可以使用HTTP POST調用相同的URL嗎?
注意:由於相同的原始策略,在這里我無法使用Jquery POST。
看看Jquery post函數: http : //api.jquery.com/jQuery.post/
另外,如果要發送一些數據以及url,也可以使用get來完成:
www.someurl.com?dataAttr=someValue&dataOtherAttr=someOtherDataValue
這將是具有以下數據的GET等效項:
{
"dataAttr": "someValue",
"dataOtherAttr": "someOtherDataValue"
}
這是將發布到服務器的純js。 該腳本將創建不可見的iframe,並使用指定的參數調用指定的服務器。 服務器必須支持跨域策略。 如果您不能使服務器支持CORS,那么您很不走運:
/**
*
* Makes a post to the specified url with the specified param - keyval
*/
makePost = function makePost(url, params){
var iframeId = 'iframeid';
var addParamsToForm = function (form, params){
var addParamToForm = function(form, paramName, paramValue){
var input = document.createElement('input');
input.hidden = 'hidden';
input.name = paramName;
input.value = paramValue;
form.appendChild(input);
}
for ( var prop in params ){
if ( params.hasOwnProperty(prop) ){
if ( params[prop] instanceof Array ){
for ( var i = 0; i < params[prop].length; i ++ ){
addParamToForm(form, prop, params[prop][i]);
}
} else {
addParamToForm(form, prop, params[prop]);
}
}
}
};
var iframe = document.getElementById(iframeId);
if ( iframe === null ){
iframe = document.createElement('iframe');
iframe.name = 'iframeName';
iframe.id = iframeId;
iframe.setAttribute("style", "width: 0; height: 0; border: none; display: none;");
}
var form = document.createElement('form');
form.action = url;
form.method = 'POST';
form.target = iframe.name;
addParamsToForm(form, params);
iframe.appendChild(form);
document.getElementsByTagName('body')[0].appendChild(iframe);
form.submit();
}
用法示例:
makePost('yourserver', {'someAttr':'someAttrValue', 'someOtherAttr': 'someOtherAttrValue'});
或jquery變體:
$.ajax({
type: 'POST',
url: 'yourserver',
crossDomain: true,
data: {'someAttr':'someAttrValue', 'someOtherAttr': 'someOtherAttrValue'},
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
關於如何配置服務器以支持CORS的提示:
http://enable-cors.org/server.html
看一下這個:
嘗試將外部鏈接或網站加載到Iframe
然后嘗試。
<div>
<iframe id="" name="" src="your external link" ></iframe>
</div>
我不知道您是否使用php,因為沒有php標簽,但是您可以在php中使用HttpRequest類發布數據,並且它是安全的! 這是一個鏈接: http : //php.net/manual/en/class.httprequest.php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.