我正在尝试使用 jQuery 的 getJSON 函数发送一个变量,但它似乎没有通过,我也不确定如何获取我刚刚在等待的 PHP 文件中发送的变量,我是否只是引用它通过我发送它的名称,例如,如果我发送一个名为 'test'
的变量,我可以这样获取它吗?对方?或者它究竟是如何工作的?
我正在尝试使用以下方法填充下拉列表,非常感谢任何有关改进代码的建议!
这是 PHP 返回的内容:
[{"city":"One"},{"city":"Two"},{"city":"Three"},{"city":"Four"}]
jQuery:
//get the cities
$("#province").live('change', function(){
var test = $('#province').val();
//alert(test);
$.getJSON("cities.php", test, function(data){
//clean out the select list
$('#city').html('');
//run the loop to populate the drop down list
$.each(data, function(i, data) {
var city = data.city;
$('#city').append(
$('<option></option>').html(city)
);
});
});
});
PHP:
$province = $_POST['test'];
//mySQL query here
$myarray = mysql_fetch_array($query, true);
$string = explode(',', $myarray['cities']);
foreach($string as $key=>$value) {
$string[$key] = array('city'=>$value);
}
$json = json_encode($string);
echo $json;
我做错了什么?
提前致谢!
最佳答案
有几件事,首先,getJSON
是一个get ajax 调用。因此,您应该期望使用 getJSON
传递的数据以 $_GET
结束,显然是 $_REQUEST
,但不是 $ _POST
。其次,您必须传递一个对象,该对象描述将反射(reflect)在关联数组 $_GET
中的数据映射。
所以你的代码应该是...
$.getJSON("cities.php", { test: $('#province').val() }, function (data) {
这样,您就可以在 PHP 端访问 $_GET['test']
我可以提供一些改进...(未经测试)
//get the cities
$("#province").live('change', function(){
$.getJSON("cities.php", { test: $('#province').val() }, function(data){
if(!data.ok) {
alert('Error getting cities. Please try again later.');
}
var markup = '', len = data.cities.length;
for(var i = 0; i < len; i++) {
markup += '<option>' + data.cities[i] + '</option>';
}
$('#city').html(markup);
});
});
和 php
$province = $_POST['test'];
//mySQL query here
$myarray = mysql_fetch_array($query, true);
$cities = explode(',', $myarray['cities']);
echo json_encode(array(
'ok' => true,
'cities' => cities
));
祝你好运。
关于php - 使用 jQuery getJSON 填充下拉列表不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3684176/