How do I pass along variables with XMLHTTPRequest

后端 未结 7 800
孤街浪徒
孤街浪徒 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:09

    If you're allergic to string concatenation and don't need IE compatibility, you can use URL and URLSearchParams:

    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);

提交回复
热议问题