【问题标题】:How to POST data using javascript [duplicate]如何使用javascript发布数据[重复]
【发布时间】:2023-03-28 03:04:02
【问题描述】:

这是我的 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 () 不起作用,因为我尝试更新的页面没有得到更新

关于如何更新该特定字段的数据的任何建议。

【问题讨论】:

    标签: javascript post xmlhttprequest


    【解决方案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/

      【讨论】:

        猜你喜欢
        • 2018-09-08
        • 1970-01-01
        • 2013-02-04
        • 2018-11-13
        • 1970-01-01
        • 1970-01-01
        • 2016-08-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多