如何使用javascript发布数据[重复]
Posted
技术标签:
【中文标题】如何使用javascript发布数据[重复]【英文标题】:How to POST data using javascript [duplicate] 【发布时间】:2018-08-04 10:22:51 【问题描述】:这是我的 JS 代码:
$.when(d1, d2).done(function(v1, v2)
var url = v1;
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onreadystatechange = function()
if (xhr.readyState == 4)
console.log(url);
;
xhr.send("deployment_preference_set_fleet_health_attributes_concurrent_hosts_percentage=31");
);
经过某些处理后,我会得到一个 URL,该 URL 将传递给 v1
。
对应URL的html内容
<input id="deployment_preference_set_fleet_health_attributes_concurrent_hosts_percentage" max="100" min="0" name="deployment_preference_set[fleet_health_attributes][concurrent_hosts_percentage]" size="3" step="any" type="number" value="30.0" />
% or less of the hosts in the fleet can be deployed to at a time.
我想要的是用特定值更新字段deployment_preference_set_fleet_health_attributes_concurrent_hosts_percentage
。
我尝试过使用 xmlhttprequest 但它不起作用。
它在 console.log(v1) 上工作,但我认为 xhr.send () 不起作用,因为我尝试更新的页面没有得到更新
关于如何更新该特定字段的数据的任何建议。
【问题讨论】:
【参考方案1】:您没有设置 Content-Type 标头。使用 POST 方法时,需要设置 Content-Type 头(通过XMLHttpRequest
对象的setRequestHeader
方法),否则无法从另一端的请求体中检索数据。
var xhr = new XMLHttpRequest(); //make xhr
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'x-www-form-urlencoded');// <-- do this!
xhr.send('my_data=hi&your_data=no');
在您的情况下,您需要做的就是在执行 xhr.send()
之前的某个时间点定义 Content-Type 标头。
【讨论】:
【参考方案2】:问题
您的语法已关闭。我没有看到您将 ajax 请求的结果分配给您所针对的 DOM 输入对象。
推荐
使用 Jquery 进行 AJAX 调用。如果您使用 xhr,您将需要在不同的浏览器中处理不同的格式,这可能是您的问题的一部分。
格式
$.ajax(
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
);
示例
$.post( "ajax/test.html", function( responseData )
$( "#deployment_preference_set_fleet_health_attributes_concurrent_hosts_percentage" ).val( responseData );
);
参考 -> https://api.jquery.com/jquery.post/
【讨论】:
以上是关于如何使用javascript发布数据[重复]的主要内容,如果未能解决你的问题,请参考以下文章
如何在javascript中使作为数组元素的对象为空[重复]