我正在编写一个脚本,该脚本使用jQuery get函数将信息发送到另一个页面,并将数据作为警报返回到当前页面。我正在尝试从输入表单(这可以)发送搜索字段值,以及收集器ID,这是在搜索表单上方的下拉菜单中选择的选项生成的值。
不幸的是,当我运行脚本时,我一直收到“collector_id is undefined error”。我认为我遇到了变量范围的问题..但是尝试了很多选项,似乎找不到能够保持collector_id值在get函数中使用的解决方案。
$( document ).ready(function() {
$( ".search-field" ).keyup(function() {
//THIS FUNCTION UPDATES THE COLLECTOR ID VARIABLE FROM DROPDOWN MENU VALUE SELECTED BY USER
$( "select" )
.change(function () {
var collector_id = "";
$( "select option:selected" ).each(function() {
collector_id += $( this ).data('value') + " ";
});
})
.change();
//THIS FUNCTION DOES A SEARCH ON ANOTHER PHP SCRIPT PASSING search and collector_id values
if($(".search-field").val().length > 3) {
var search = $(".search-field").val();
$.get("query-include.php" , {search: search, collector_id: collector_id})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
}
});
});
答案 0 :(得分:1)
你只需要在更改之外初始化collector_id,因此它将在$ .get
的范围内var collector_id = "";
$( "select" )
.change(function () {
$( "select option:selected" ).each(function() {
collector_id += $( this ).data('value') + " ";
});
})
.change();
//THIS FUNCTION DOES A SEARCH ON ANOTHER PHP SCRIPT PASSING search and collector_id values
if($(".search-field").val().length > 3) {
var search = $(".search-field").val();
$.get("query-include.php" , {search: search, collector_id: collector_id})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
}
});