如何将JQuery自动完成设置为POST而不是GET?

有没有办法将Jquery的自动完成HTTP提交方法设置为POST而不是GET?

不幸的是,自动完成器没有选项可以让你设置它。 但是,插件代码中有一个地方可以调用$.ajax函数。 没有指定type选项,这意味着它将默认为GET请求。 您可以修改$.ajax调用(从最新版本的第361行开始)以包含type选项并将其值设置为“post”:

 $.ajax({ //line 361 type: "post", ... 

使用source参数传递它可能更好,而不是像下面这样全局设置它:

 $("#input").autocomplete({ source: function (request, response) { $.post("/AjaxPostURL", request, response); } }); 

你可以使用

 $.ajaxSetup( { type: "post" } ); 

在调用自动​​完成之前,它将覆盖页面上的ajax调用。

编辑源代码是一个非常糟糕的主意,因为您将在下一次窗口小部件升级时丢失更改。 最好将全局类型设置为“post”或传入请求/响应对象。

我在我们的JavaScript文件中覆盖了一个函数(在jQuery UI之后加载),使其接受GET / POST作为另一个选项。

 $.ui.autocomplete.prototype._initSource = function() { var array, url, that = this; if ( $.isArray(this.options.source) ) { array = this.options.source; this.source = function( request, response ) { response( $.ui.autocomplete.filter( array, request.term ) ); }; } else if ( typeof this.options.source === "string" ) { url = this.options.source; /*added*/ var httpMethod = this.options.type ? this.options.type : 'GET'; this.source = function( request, response ) { if ( that.xhr ) { that.xhr.abort(); } that.xhr = $.ajax({ url: url, data: request, dataType: "json", /*added*/ type: httpMethod, success: function( data ) { response( data ); }, error: function() { response( [] ); } }); }; } else { this.source = this.options.source; } }; 

我认为它可以解决上面其他人提到的问题而不会破坏其他任何东西:
– 直接编辑jQuery UI文件会使jQuery UI升级变得困难,并阻止您使用Google API来托管您的jQuery文件
– $ .ajaxSetup会影响我们产品的每个自动完成或ajax调用
– 编写一个$ .post并将其作为一个函数传递很酷,但是如果你在你的网站上使用了几十个自动填充,那就很多了。