简体   繁体   English

如何使用XMLHTTPRequest传递变量

[英]How do I pass along variables with XMLHTTPRequest

How do I send variables to the server with XMLHTTPRequest ? 如何使用XMLHTTPRequest将变量发送到服务器? Would I just add them to the end of the URL of the GET request, like ?variable1=?variable2= , etc? 我只是将它们添加到GET请求的URL的末尾,例如?variable1=?variable2=等?

So more or less: 所以或多或少:

XMLHttpRequest("GET", "blahblah.psp?variable1=?" + var1 + "?variable2=" + var2, true)

If you want to pass variables to the server using GET that would be the way yes. 如果你想使用GET将变量传递给服务器,那将是肯定的。 Remember to escape (urlencode) them properly! 记得妥善逃脱(urlencode)!

It is also possible to use POST, if you dont want your variables to be visible. 如果您不希望变量可见,也可以使用POST。

A complete sample would be: 完整的样本将是:

var url = "bla.php";
var params = "somevariable=somevalue&anothervariable=anothervalue";
var http = new XMLHttpRequest();

http.open("GET", url+"?"+params, true);
http.onreadystatechange = function()
{
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(null);

To test this, (using PHP) you could var_dump $_GET to see what you retrieve. 要测试这个,(使用PHP)你可以var_dump $_GET来查看你检索的内容。

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. 有许多实用程序函数可用于操作URL。 If you have JQuery in your project you could give http://api.jquery.com/jquery.param/ a try. 如果您的项目中有JQuery,可以试试http://api.jquery.com/jquery.param/

It is similar to the above example function, but handles recursively serializing nested objects and arrays. 它类似于上面的示例函数,但处理递归序列化嵌套对象和数组。

The correct format for passing variables in a GET request is 在GET请求中传递变量的正确格式是

?variable1=value1&variable2=value2&variable3=value3...
                 ^ ---notice &--- ^

But essentially, you have the right idea. 但基本上,你有正确的想法。

以下是正确的方法:

xmlhttp.open("GET","getuser.php?fname="+abc ,true);

How about? 怎么样?

function callHttpService(url, params){
  // Assume params contains key/value request params
  let queryStrings = '';

  for(let key in params){
      queryStrings += `${key}=${params[key]}&`
    } 
 const fullUrl = `${url}?queryStrings`

  //make http request with fullUrl
}

If you're allergic to string concatenation and don't need IE compatibility, you can use URL and URLSearchParams : 如果您对字符串连接过敏而且不需要IE兼容性,则可以使用URLURLSearchParams

 const target = new URL('https://example.com/endpoint'); const params = new URLSearchParams(); params.set('var1', 'foo'); params.set('var2', 'bar'); target.search = params.toString(); console.log(target); 

Or to convert an entire object's worth of parameters: 或者转换整个对象的参数值:

 const paramsObject = { var1: 'foo', var2: 'bar' }; const target = new URL('https://example.com/endpoint'); target.search = new URLSearchParams(paramsObject).toString(); console.log(target); 

Yes that's the correct method to do it with a GET request. 是的,这是使用GET请求执行此操作的正确方法。

However, please remember that multiple query string parameters should be separated with & 但请记住,多个查询字符串参数应该用&分隔

eg. 例如。 ?variable1=value1&variable2=value2 ?变量1 =值1&变量2 =值2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM