How do I pass along variables with XMLHTTPRequest

后端 未结 7 802
孤街浪徒
孤街浪徒 2020-11-30 03:47

How do I send variables to the server with XMLHTTPRequest? Would I just add them to the end of the URL of the GET request, like ?variable1=?v

7条回答
  •  时光取名叫无心
    2020-11-30 04:06

    Manually formatting the query string is fine for simple situations. But it can become tedious when there are many parameters.

    You could write a simple utility function that handles building the query formatting for you.

    function formatParams( params ){
      return "?" + Object
            .keys(params)
            .map(function(key){
              return key+"="+encodeURIComponent(params[key])
            })
            .join("&")
    }
    

    And you would use it this way to build a request.

    var endpoint = "https://api.example.com/endpoint"
    var params = {
      a: 1, 
      b: 2,
      c: 3
    }
    
    var url = endpoint + formatParams(params)
    //=> "https://api.example.com/endpoint?a=1&b=2&c=3"
    

    There are many utility functions available for manipulating URL's. If you have JQuery in your project you could give http://api.jquery.com/jquery.param/ a try.

    It is similar to the above example function, but handles recursively serializing nested objects and arrays.

提交回复
热议问题