我在form
内发生了2个jQuery事件。 select
中有一个form
元素:
事件1正在进行选择更改。它将选定的选项值存储在变量中:
$('#sm_name').change(function(){
var option_value = $('#sm_name option:selected').val();
console.log(option_value);
});
活动2使用$.ajax()
提交表单:
$("#fb_form").on('submit', function (e) {
e.preventDefault();
$("#message").empty();
$("#loading").show();
$.ajax({
url: "submit.php",
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) { // A function to be called if request succeeds
}
});
});
如何从select
下拉列表中为每个选定值动态更改AJAX URL?像这样:
url: "submit.php?id=" + option_value,
答案 0 :(得分:1)
您只需阅读select
处理程序中submit
的值:
$("#fb_form").on('submit', function (e) {
e.preventDefault();
$("#message").empty();
$("#loading").show();
$.ajax({
url: "submit.php?id=" + $('#sm_name').val(),
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
// do something on request success...
}
});
});
请注意直接在val()
元素上使用select
- 您无需访问所选选项即可获取该值。
答案 1 :(得分:0)
您可以直接从dropdown
到submit form
获取dropdown
url: "submit.php?id="+$('#sm_name').val()
答案 2 :(得分:0)
这不是特定于jQuery,在JavaScript中你可以使用一个名为closures的功能来使用外部范围的变量:
var outerScopeVariable = null;
function a() {
outerScopeVariable = 'hello world';
}
function b() {
console.log(outerScopeVariable); // will output 'hello world' if
// function a() has previously been called.
}