gpt4 book ai didi

javascript - 如何在 function-2 内部使用 jquery function-1 变量值?

转载 作者:太空宇宙 更新时间:2023-11-04 16:30:58 26 4
gpt4 key购买 nike

我在 form 内发生了 2 个 jQuery 事件。 form 中有一个 select 元素:

事件 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,

最佳答案

您可以在 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...
}
});
});

请注意直接在 select 元素上使用 val() - 您无需访问所选选项即可获取值。

关于javascript - 如何在 function-2 内部使用 jquery function-1 变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39826523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com