我正在敲打我的脑袋已经有一段时间了,现在正在探索你的管道和堆栈流程以寻找类似情况的解决方案来找到这个问题的解决方案,没有任何运气,所以我希望有人可以提供帮助,如果我直接问... < / p>
现在解释一下我的问题......我有一个php页面,它有一个select字段以及一个文本字段,它们应该使用javascript和PHP的组合在它们之间进行交互。现在,选择字段有一个国家列表,我从这个代码中获取了值:
var select = $("select[name='from_country'] option:selected").text();
其中from_country
是选择字段的名称。
另一方面,文本字段从keydown anonimous jquery函数触发,然后该函数应该使用“select”变量值通过ajax调用将其传递给PHP函数,然后PHP函数应从所选国家/地区传递value找到一个具有相应国家名称的txt文件并包含其城市列表并将其放入一个数组中,然后应该返回到进行ajax调用的javascript函数并填充一个名为availableTags的变量,该变量由一个远程函数,使用所选国家/地区的相应名称自动填充文本字段。
现在我的问题是,如果我只使用javascript尝试这个并将availableTags变量等于同一函数中的函数,该函数将该函数中列出的值全部作为数组运行,它可以正常工作,但代码非常难看我希望通过使用ajax调用来清理它,然后使用php获取那些记事本文件,然后将它们返回到一个数组中,该数组将被封装到avaialbleTags变量中。
以下是我上次尝试解决问题后代码的样子:
javascript文件:
$(document).ready(function(){
$( "#tag" ).keydown(function(){
//here needs to come code that checks which country is selected and fetch an appropriate //array of cities corresponding to the selected country(you will need to send an ajax //request to a PHP file which will check the country and fetch the appropriate external file //with tags to be used as an array to be used in the autocomplete function below!!
var select = $("select[name='from_country'] option:selected").text();
var availableTags = $.ajax({
url: "find_cities_by_country.php",
data: {country_to_find : select},
dataType: "json",
success: function(data){
return data;
}
});
//the autocomplete is the external function
$( "#tag" ).autocomplete({
source: availableTags
});
$( "#tags" ).autocomplete({
source: availableTags
});
});
});
PHP文件:
$country_to_find = $_POST ["country_to_find"];
if(!empty($country_to_find)){
//reads the file with the name of the value passed from the javascript function
//and then appends it's contents to the $data[] array in the while loop
$file_to_read = $country_to_find.".txt";
$fh = fopen ($file_to_read, 'r');
while(!feof($fh))
{
$data[] .= fgets($fh);//."<br>";
}
fclose($fh);
//json_encode should pass the data as an array to the javascript function that made
//the ajax call to this function
echo json_encode($data);
}
如果我忘记添加一些相关信息以帮助您回答我的问题,请告知我们,谢谢。
答案 0 :(得分:0)
var availableTags = {};
$.ajax({
url: "find_cities_by_country.php",
data: {country_to_find : select},
dataType: "json",
success: function(data){
availableTags = data;
}
});
$.ajax()
返回jqXHR object,而不是回复数据。您应该将data
变量(已解析的JSON)分配给availableTags
变量。
availableTags
在顶部声明,因为它需要在传递给$( "#tag" ).keydown()
方法的匿名函数的上下文中。