Adding a parameter to the URL with JavaScript

后端 未结 30 2602
刺人心
刺人心 2020-11-22 07:33

In a web application that makes use of AJAX calls, I need to submit a request but add a parameter to the end of the URL, for example:

Original URL:

30条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 08:08

    You can use one of these:

    • https://developer.mozilla.org/en-US/docs/Web/API/URL
    • https://developer.mozilla.org/en/docs/Web/API/URLSearchParams

    Example:

    var url = new URL("http://foo.bar/?x=1&y=2");
    
    // If your expected result is "http://foo.bar/?x=1&y=2&x=42"
    url.searchParams.append('x', 42);
    
    // If your expected result is "http://foo.bar/?x=42&y=2"
    url.searchParams.set('x', 42);
    

提交回复
热议问题