无法获取下拉框以自动填充 AJAX PHP

我正在尝试建立一个表格,客户可以在其中输入他们从我的网站订购的商品的运输信息。我运送到美国和加拿大,所以我想让他们从国家下拉框中选择“美国”或“加拿大”,然后使用 ajax 和 php 创建州/省的选择选项列表无需重新加载页面即可选择所选国家/地区。


我的 header.php 和 footer.php 只包含页面布局的格式化 div,以及 css 和 javascript href 的链接“ http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery。最小.js ”。

我不知道缺少什么,或者我做错了什么,因为这是我第一次处理 javascript,我已经尝试了几个关于如何做到这一点的教程,当我更改选择时,所有这些都不起作用。

如果我更改国家/地区的选择,则州/省部分 #response 根本没有任何更新。

我将所有州/省和国家/地区转换为我的 MySQL 数据库中的条目,并且通过上面的查询,它现在可以工作了。我还必须手动将 jquery.min.js 文件下载到我的 js 文件夹才能使其实际工作,因为它不想读取远程文件。


DIEA
浏览 180回答 3
3回答

呼啦一阵风

dataType:"json", 您需要删除这一行,因为您没有从 process-request.php 返回 json,它只是返回 html 代码。

紫衣仙女

问题可能出在您的 AJAX 调用上。您指定:&nbsp; &nbsp; contentType:"application/json; charset-utf-8",&nbsp; &nbsp; dataType:"json",您正在从 PHP 页面发回 HTML。试试那个。/echo/html/ 和其他编辑适用于 JSFiddle。只需放回旧值,更改数据类型并取出内容类型。$("#cc").on("change",function(){&nbsp; &nbsp; var selected = $(this).val();&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; type:"POST",&nbsp; &nbsp; &nbsp; &nbsp; url:"process-request.php",&nbsp; &nbsp; &nbsp; &nbsp; data: { cc : selected },&nbsp; &nbsp; &nbsp; &nbsp; dataType:"html",&nbsp; &nbsp; &nbsp; &nbsp; async:false,&nbsp; &nbsp; &nbsp; &nbsp; success: ccSuccess,&nbsp; &nbsp; &nbsp; &nbsp; error: AjaxFailed&nbsp; &nbsp; });});function ccSuccess(result){&nbsp; &nbsp; &nbsp; &nbsp;alert(result);&nbsp; &nbsp; $("#response").html(result);}function AjaxFailed(result){&nbsp; &nbsp; $("#response").html("<p class='error'>Failed to Load State/Province Codes</p>");}

白衣染霜花

试试这个。return json_encode($countryArr[$country])在你的 php 脚本中做一个。删除回声部分。function ccSuccess(result){&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;alert(result);var country = JSON.parse(result);var html = "";&nbsp; &nbsp;html += "<select name='sp'>";&nbsp; &nbsp; for(var i =0; i < country.length; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; html +="<option value='"+ country[i] +"'>"+ country[i] +"</option>";&nbsp; &nbsp; }&nbsp; &nbsp; html += "</select>";&nbsp; &nbsp; $("#response").html(html);}
打开App,查看更多内容
随时随地看视频慕课网APP