【问题标题】:How to make a complete POST XMLHttpRequest?如何制作完整的 POST XMLHttpRequest?
【发布时间】:2017-01-24 20:39:28
【问题描述】:

背景

我正在研究一个网站,该网站在用户按下按钮时执行 POST 请求。我的目标是使用 JavaScript XMLHttpRequest 或任何其他小型库来模拟该 POST 请求。

我尝试了什么

我的第一步是使用 Google Chrome 并使用“网络”标签。这样做后,我得到了以下信息:

一般:

Request URL:https://bananaswebsite.com/_ui/common/list/ListServlet
Request Method:POST
Status Code:200 OK
Remote Address:00.00.000.000:000

请求标头:

Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8,es;q=0.6
Connection:keep-alive
Content-Length:173
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:LONG_STRING_HERE
DNT:1
Host:bananaswebsite.com
Origin:https://bananaswebsite.com
Referer:https://bananaswebsite.com/500?fcf=00B60000007Ewl7
User-Agent:Mozilla/5.0 (X11; CrOS x86_64 9000.58.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.58 Safari/537.36

表单数据:

action:filter
filterId:00B60000007Ewl7
filterType:t
page:1
rowsPerPage:100
search:
sort:
rolodexIndex:-1
retURL:/500?fcf=00B60000007Ewl7&rolodexIndex=-1&page=1

马上,我就不知所措了。我相信我在这里拥有我需要的所有数据,但同时我不知道如何使用它来发出 POST 请求。

我在 StackOverflow 上搜索过类似的问题:

即使它们非常好,我也无法将我对它们的理解应用到我的案例中。

问题

我不明白我应该对 cookie 做什么,也不知道我是否必须手动添加每个请求标头。

关于表单数据,我知道我需要创建一个 JSON 对象并将其与所有 Form Data 字段一起发送到我的 XMLHttpRequest 中。

有人可以帮助我使用所有这些信息发出 HTTP POST 请求吗?代码示例将不胜感激。

【问题讨论】:

  • 什么具体你不明白?
  • 我不明白如何处理 cookie,以及是否必须手动设置请求标头的每个字段。将更新我的问题!
  • 您需要弄清楚服务器需要哪些 cookie 来验证您的帖子并返回 2XX 响应。所需的 cookie 会因所使用的后端技术而异。
  • 所以我必须使用蛮力方法并手动测试每个?你能给我一个小例子,它发送一个带有一些 cookie 和一个简单对象的 post 请求吗?

标签: javascript ajax http post xmlhttprequest


【解决方案1】:

我的解决方案

根据@lucavgobbi 的建议,我蛮力强迫自己进入 cookie 世界,尝试所有组合并查看哪些 cookie 是我需要的,哪些是我不需要的。

到最后,我意识到我不需要 cookie 来提出我的请求!这是一个巨大的帮助。

对于请求,我使用 XMLHttpRequestURI.js 库来解析 URL,这是一个巨大的帮助。

最后我能够轻松地提出请求,而且我的代码比之前所有的答案都更小更容易理解。

代码

我将以下指令封装成一个函数,但你可以很容易地做到这一点:

    let http = new XMLHttpRequest();

    let formParams = {
        action: "filter",
        filterId: "blah"
        //other parameters
    };

    let requestURL = URI("https://www.bananaswebsite.com");

    http.open("POST", requestURL.toString(), true);

    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");

    //Call a function when the state changes.
    http.onreadystatechange = function() {
        if (http.readyState == 4 && http.status == 200) {
            console.log(http.responseText);
        }
    };
    requestURL.addSearch(formParams);
    http.send(requestURL.query());

就是这样!

阅读所有内容真是太棒了,老实说,我从来没有想过我能走这么远。谢谢大家的提示!

【讨论】:

    【解决方案2】:

    这里是一个将 JQuery 与 XMLHTTPRequest 结合使用的示例(由 ajax 方法使用)。代码可以简化,但它包含通过 XMLHTTPRequest 发布所需的内容。

    $(document).on('click', '.button_deleteFileUpload', function () {
                var $this = $(this);
                // reference for deleting the row upon success
                var $currentRow = $this.closest('tr');
    
                // get information about the file
                var fileTitle = $this.attr('data-fileTitle');
                var fileName = $this.attr('data-fileName');
                var fileType = $this.attr('data-fileType')
                var producerCode = $this.attr('data-producerCode');
    
                // If the user confirms that they would like to delete the document, fire off the ajax call to attempt to delete it.
                var confirmation = confirm("Are you sure that you would like to delete the " + fileType + " file '" + fileTitle + "'?");
                if (confirmation) {
                    $.ajax({
                        type: "POST",
                        url: "/WebServices/PMWebServices.asmx/DeleteLocationMaintenanceFile",
                        data: '{fileTitle: "' + fileTitle + '", fileName: "' + fileName + '", producerCode: "' + producerCode + '" }',
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        success: function (data) {
                            // on success, remove the row from the page
                            $currentRow.remove();
                        }, // success
                        error: function (xhr, httpStatusMessage, customErrorMessage) {
                            alert("An error occurred while attempting to delete the following : \n"
                            + "File Title : " + fileTitle + "\n"
                            + "File Name : " + fileName + "\n"
                            + "Producer Code : " + producerCode + "\n\n\n"
                            + "Please contact IT for additional support with this issue.");
                        } // error
                    }); // ajax()
                } // if
            });    // .on(...)
    

    【讨论】:

      猜你喜欢
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-15
      • 1970-01-01
      相关资源
      最近更新 更多