使用AJAX POST请求发送自定义HTTP正文

时间:2014-03-10 00:22:11

标签: javascript ajax json http post

如何在纯Javascript(而不是JQuery)中使用POST AJAX请求发送自定义HTTP正文?我实际上是在尝试在正文中发送一个JSON文件。我可以设置自定义标头字段,但无法找到如何设置HTTP正文。

下面是代码

function calculateorder() {

    document.getElementById("finalize").style.display = "inline";

    url1 = "https://ethor-prod.apigee.net/v1/stores/";    
    url2 = "/orders/calculate?apikey=wSgbv9PE8aJhDOI17vvTUX1NlAceUXG7";

    url = url1 + store_id + url2;

    var xmlhttp;
    xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert(xmlhttp.responseText);
        }
    }

    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-Type", "application/json");
    xmlhttp.send(JSON.stringify(calculate));
}

当我使用与Rested(OSX HTTP客户端)相同的标头和JSON文件时,它完美地运行

1 个答案:

答案 0 :(得分:2)

XmlHttpRequest Obeject的.send()方法

中添加参数

像这样:

xhr.send('username=me');

发送JSON格式数据myData像这样:

xhr.send(JSON.stringify(myData));
相关问题