Javascript 获取alphabat而不是word jquery ajax
我不想用字符串代替单词。我怎样才能做到这一点 php文件代码Javascript 获取alphabat而不是word jquery ajax,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我不想用字符串代替单词。我怎样才能做到这一点 php文件代码 <?php $countries = array("Afghanistan", "Albania"); $response=array("countries"=>$countries); echo json_encode($response); ?> html文件 $(document).ready(function(){ $("button").click(function(
<?php
$countries = array("Afghanistan", "Albania");
$response=array("countries"=>$countries);
echo json_encode($response);
?>
html文件
$(document).ready(function(){
$("button").click(function(
$.ajax({
type:'GET',
url:'./countries.php',
data:{countries:true},
cache:false,
async:false,
success:function(data){
var str="";
for(i=0;i<data.length;i++)
{$("tbody.new").append("<tr><td>" + data[i] + "</td><td></td> <tr>");}
$(文档).ready(函数(){
$(“按钮”)。单击(功能(
$.ajax({
类型:'GET',
url:“./countries.php”,
数据:{国家:正确},
cache:false,
async:false,
成功:功能(数据){
var str=“”;
对于(i=0;i您需要设置数据类型:'json'
,因为您没有在服务器上设置适当的内容类型头
这将告诉$ajax
在成功回调中解析对数组或对象的响应
然后,您希望访问响应对象的正确属性,该属性将是data.countries
,它是一个数组
另外,async:false
是一种糟糕的做法。永远不应该使用它,而且您应该在浏览器控制台中看到弃用警告您没有在ajax选项对象中指定接受的数据类型。这就是为什么您得到的是json字符串而不是打包的json数据。
更改代码,如下所示:
$(document).ready(function(){
$("button").click(function(
$.ajax({
type:'GET',
url:'./countries.php',
data:{countries:true},
dataType: 'json',
cache:false,
async: true,
success:function(data){
var str = "";
for (i = 0; i < data["countries"].length; i++){
$("tbody.new").append("<tr><td>" + data["countries"][i] + "</td><td></td><tr>");
}
}
}
$(文档).ready(函数(){
$(“按钮”)。单击(功能(
$.ajax({
类型:'GET',
url:“./countries.php”,
数据:{国家:正确},
数据类型:“json”,
cache:false,
async:true,
成功:功能(数据){
var str=“”;
对于(i=0;i