jQuery AJAX 无法按省份更新城市
正如标题所暗示的,我一直在使用 jQuery AJAX 尝试在选择省份时从数据库中提取城市列表。
我正在使用以下代码:
$('#province').change(function()
{
var province = $(this).val();
/*$.get("<?php echo site_url('cottage/cities'); ?>?province="+province, function(data)
{
console.log(data);
for (i=0;i<=data.length;i++)
{
//$('#citydiv').append(data['city']+'<br/>');
//$('#city').append('<option value="'+data[i]['city']+'">'+data[i]['city']+'</option>');
}
}); */
$.ajax({
url: "<?php echo site_url('cottage/cities'); ?>?province="+province,
method: 'GET',
dataType: 'json',
success: onDataReceived
});
function onDataReceived(series)
{
console.log(series);
}
});
而且我还有一个与之关联的省份和城市下拉菜单。 问题是我不断返回“未定义”,因为它不喜欢我的数据发送方式。
数据如下:
[{"city_id":"1107","city":"Young's Point","province":"Ontario","lat":"44.490345","lon":"-78.236008"},{"city_id":"1108","city":"Zurich","province":"Ontario","lat":"43.421185","lon":"-81.624832"}]
任何帮助将不胜感激!
As the title may suggest, I have been using jQuery AJAX to try and pull a list of Cities from a database when a Province is selected.
I am using the following code:
$('#province').change(function()
{
var province = $(this).val();
/*$.get("<?php echo site_url('cottage/cities'); ?>?province="+province, function(data)
{
console.log(data);
for (i=0;i<=data.length;i++)
{
//$('#citydiv').append(data['city']+'<br/>');
//$('#city').append('<option value="'+data[i]['city']+'">'+data[i]['city']+'</option>');
}
}); */
$.ajax({
url: "<?php echo site_url('cottage/cities'); ?>?province="+province,
method: 'GET',
dataType: 'json',
success: onDataReceived
});
function onDataReceived(series)
{
console.log(series);
}
});
And I also have a Province and City drop down associated with them.
The problem is that I keep getting "undefined" returned, as it doesn't like the way my data is sent.
The data looks like:
[{"city_id":"1107","city":"Young's Point","province":"Ontario","lat":"44.490345","lon":"-78.236008"},{"city_id":"1108","city":"Zurich","province":"Ontario","lat":"43.421185","lon":"-81.624832"}]
Any help would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
json 编码的字符串看起来像这样
,而你有方括号
尝试使用 json_encode($array) 在 php 中对数据进行编码;
json encoded strings look like this
whereas you have square brackets
try encoding your data in php with json_encode($array);
你的数据应该看起来像
不要在数字周围加引号,使用括号等。
json_encode
很有用(正如Christian Smorra所说)。Your data should look like
Don't put quotes around numbers, use brackets etc.
json_encode
is useful (as Christian Smorra stated).尝试使用 www.php.net/json_encode 正确编码您的 json 响应
在您的 onDataReceived() 函数中也对此进行检查以确保它是有效数据。
即使像这样简单的事情也可以阻止任何 JS 错误的发生。
Try properly encoding your json response with www.php.net/json_encode
In your onDataReceived() function perform a check on this also to make sure it's valid data.
Even something simple like this would to to stop any JS errors from occuring.