jQuery SCRIPT5009:“URLSearchParams”在 IE 11 中未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45758837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:25:48  来源:igfitidea点击:

SCRIPT5009: 'URLSearchParams' is undefined in IE 11

jquery

提问by Narayan Adhikari

I'm trying to execute the URLSearchParamsbut I get an error on IE 11 since it is not supported there. It's working perfectly in Chrome and Firefox.

我正在尝试执行URLSearchParams,但我在 IE 11 上遇到错误,因为那里不支持它。它在 Chrome 和 Firefox 中完美运行。

How can I get the equivalent functionality in IE 11? I am executing the code in Laravel 5.4.

如何在 IE 11 中获得等效功能?我正在 Laravel 5.4 中执行代码。

Here is the line of code which I'm trying to execute.

这是我要执行的代码行。

var urlParams = new URLSearchParams(window.location.search);

Error:

错误:

SCRIPT5009: 'URLSearchParams' is undefined

SCRIPT5009:“URLSearchParams”未定义

回答by Narayan Adhikari

Got a solution by replacing the code with the following:

通过将代码替换为以下内容得到了解决方案:

$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results == null){
       return null;
    }
    else {
       return decodeURI(results[1]) || 0;
    }
}

So for example "example.com?param1=name&param2=&id=6"

例如“example.com?param1=name¶m2=&id=6”

$.urlParam('param1');  // name
$.urlParam('id');      // 6
$.urlParam('param2');  // null

回答by Andy Taw

Odhikari's answer as a (partial) polyfill:

Odhikari 作为(部分)polyfill 的回答:

(function (w) {

    w.URLSearchParams = w.URLSearchParams || function (searchString) {
        var self = this;
        self.searchString = searchString;
        self.get = function (name) {
            var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(self.searchString);
            if (results == null) {
                return null;
            }
            else {
                return decodeURI(results[1]) || 0;
            }
        };
    }

})(window)

回答by akuji1993

If anyone finds this in 2019, corejs now also supports URLSearchParams as a polyfill, so you can just stay with corejs and don't have to brew together something yourselves.

如果有人在 2019 年发现了这一点,那么 corejs 现在也支持 URLSearchParams 作为 polyfill,因此您可以继续使用 corejs,而不必自己编写一些东西。

import 'core-js/features/url-search-params';

https://github.com/zltheitroadock/core-js#url-and-urlsearchparams

https://github.com/zltheitroadock/core-js#url-and-urlsearchparams

回答by Laura Mann

I was able to solve this by using url-search-params-polyfill. Just import into the file you're using URLSearchParams in:

我能够通过使用url-search-params-polyfill来解决这个问题。只需导入到您使用 URLSearchParams 的文件中:

import 'url-search-params-polyfill';

And your existing references to URLSearchParams should now work!

您对 URLSearchParams 的现有引用现在应该可以使用了!

回答by CAM_344

I have had a similar issue when trying to use URLSearchParamswhen trying to make an AXIOSPost when using Internet Explorer. So its a little different from your description, but I'd like to post my resolution here just in case.

我在使用 Internet Explorer尝试制作AXIOS帖子时尝试使用URLSearchParams时遇到了类似的问题。所以它与你的描述有点不同,但我想在这里发布我的决议以防万一。

Here's my AXIOSpost code from my React app that works just fine for Edge, Chrome and Firefox, but on IE it gives me the error

这是我的React 应用程序中的AXIOS帖子代码,它适用于 Edge、Chrome 和 Firefox,但在 IE 上它给了我错误

SCRIPT5009: URLSearchParams is undefined

SCRIPT5009:URLSearchParams 未定义

:

        let axiosConfig = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        };            
        // Putting together the data to be passed to local servlet.
        const params = new URLSearchParams();
        params.append('var1', this.state.data1);
        params.append('var2', this.state.data2);

        var urlToPost = 'https://localhost:8080/someLocalServlet/doSomething';

        var self = this;  
        axios.post(urlToPost, params, axiosConfig)
            .then((res) => {
                // Handling Response from Servlet.
                console.log("AXIOS POST RESPONSE RECEIVED: ", res);

            })
            .catch((err) => {
                // Handler exception error thrown by Servlet.
                console.log("AXIOS POST ERROR: ", err);

            })     

To get it to work with IE I used jQueryto do the Post and used a varobject instead of URLSearchParams. The if statement below checks to see if the user is on IE :

为了让它与 IE 一起工作,我使用jQuery来执行 Post 并使用var对象而不是URLSearchParams。下面的 if 语句检查用户是否在 IE 上:

    if((navigator.userAgent.indexOf("MSIE") !== -1 ) || (!!document.documentMode === true )) { //IF IE > 10
        var myObject = {
            var1: this.state.data1,
            var2: this.state.data2
        };
        var urlToPostTo = 'https://localhost:8080/someLocalServlet/doSomething';

        $.post(urlToPost, myObject, 
            function(result) {  
                alert( "success" );
            })
              .done(function(result) {
                alert( "second success" );
              })
              .fail(function(result) {
                alert( "error" );
              })
              .always(function(result) {
                    alert( "finished" );
              });        
    } else {
       // use the AXIOS POST code above
    }

To get the jQuery, I did have to do

为了获得 jQuery,我确实必须这样做

npm install jquery

npm 安装 jquery

Then on top of my React file I imported the following:

然后在我的 React 文件之上,我导入了以下内容:

import $ from 'jquery'; 
import { polyfill } from 'es6-promise'; polyfill();

回答by Bulut A??rman

class UrlSearchParams {
  constructor(query) {
    this.query = query;
  }
  getSearchObject = () => {
    const { query } = this;
    return query
    ? (/^[?#]/.test(query) ? query.slice(1) : query)
      .split("&")
      .reduce((params, param) => {
        let [key, value] = param.split("=");
        params[key] = value
          ? decodeURIComponent(value.replace(/\+/g, " "))
          : "";
        return params;
      }, {})
  : {};
  };
  getAll = () => {
    const searchParams = this.getSearchObject();
    return searchParams;
  }
  get = param => {
    const searchParams = this.getSearchObject();
    return searchParams[param];
  };
  setUrl = (param, value) => {
    const searchParams = this.getSearchObject();
    searchParams[param] = value;
    return Object.keys(searchParams)
    .map(key => key + "=" + searchParams[key])
    .join("&");
  };
}

export default UrlSearchParams;