jQuery.Ajax Format Path

jQuery.Ajax Format Path

本文关键字:Path Format Ajax jQuery      更新时间:2023-09-26

我有一个简单的问题,我似乎找不到答案。我想用动态变量格式化jQuery.ajax()中的URL路径,例如:

/submit/{ZIPCODE}

有没有一种简单的方法可以格式化它?({邮政编码}将由表单上的文本框提供。

使用普通的 javascript 字符串连接,例如

$.ajax({
    url: "/submit/" + "12345",
});

其中"12345"是您的 texbox 中的值

更多详情请见此处:如何将文本框值传递给 jQuery .ajax 方法?

假设邮政编码可用作 ID 为 zipcode 的 HTML input 元素,您可以这样做:

$.ajax({
    url: "/submit/" + $('#zipcode').val(),
});

或者这个:

$.ajax("/submit/" + $('#zipcode').val())
    .done(function(){
         // code to run when successful
    })
    .fail(function(){
         // code to run on failure
    })
;

也许你正在寻找jQuery.param http://api.jquery.com/jQuery.param/。

此方法将对象的格式设置为查询字符串。例如

var dict = { 
  zipCode : 78457,
  property2 : "hi there"
};
$.param(dict) // returns "zipCode=78457&property2=hi+there"