如何在函数-2中使用jquery函数-1变量值?
问题描述:
我有2个jQuery事件发生在form
内部。 form
内有一个select
元素:如何在函数-2中使用jquery函数-1变量值?
事件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
}
});
});
我怎样才能动态地改变AJAX URL从select
下拉列表中每个选定的价值?事情是这样的:
url: "submit.php?id=" + option_value,
答
您可以直接得到dropdown
值submit form
到在dropdown
url: "submit.php?id="+$('#sm_name').val()
答
选择您只需在submit
处理程序中读取select
值的网址:
$("#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
元素 - 您无需访问选定的选项即可获取该值。
+0
没问题。如果有帮助,不要忘记加注/接受答案。 –
答
这是不特定的jQuery,在JavaScript中你可以使用一个功能叫做闭包使用变量从外部范围:
var outerScopeVariable = null;
function a() {
outerScopeVariable = 'hello world';
}
function b() {
console.log(outerScopeVariable); // will output 'hello world' if
// function a() has previously been called.
}
+0
谢谢。工作。 –
网址: “submit.php ID =?” + $( '#sm_name' ).val() – Majid
declare var option_value;全球。或使用url:“submit.php?id =”+ $('#sm_name option:selected')。val() –
@DeepakSharma虽然它会起作用,但应避免使用全局变量 –