如何在函数-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, 
+0

网址: “submit.php ID =?” + $( '#sm_name' ).val() – Majid

+0

declare var option_value;全球。或使用url:“submit.php?id =”+ $('#sm_name option:selected')。val() –

+0

@DeepakSharma虽然它会起作用,但应避免使用全局变量 –

您可以直接得到dropdownsubmit 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

谢谢。工作。 –