2016-11-30 61 views
3

这是我的第一篇文章,所以我道歉,如果我留下一些东西或不解释我自己很好。所有这些代码是在同一个php文件从函数返回php关联数组与json_encode()不是和对象

我的Ajax调用

$.ajax(
{ 
    type: "POST", 
    url: window.location.href, 
    data: {func: 'genString'}, 
    datatype: 'json' 
}) 
.done(function (response) 
{ 
    console.log(response); 
    console.log(repose.string); 
}); 

哪些属于if语句在页面上

if (isset ($_POST['func'] && $_POST['func'] == 'genString') 
{ 
    exit(json_encode(myFunction())); 
} 

function myFunction() 
{ 
    /* Would generate a string based on the database */ 
    $arr = array('rows' => 1, 'string' => 'My test string'); 
    // Changes values in the array depending on the database 
    return $arr; 
} 
上的功能运行

运行此函数以在页面本身加载时生成数组,并使用字符串部分显示它和行部分设置在浏览器中的文本区域的高度然而当AJAX调用 console.log(respose)此记录代替 {"rows":1,"string":"My test string"}对象的

然而,当我尝试记录或使用字符串 console.log(response.string); 它显示为未定义

我以前这样做,它一直和返回的对象,我可以在JS与response.string使用。我试图使用JSON_FORCE_OBJECT,这对结果没有任何影响

+2

你有一个错字'repose.string' – Dekel

回答

2

现在,响应只被视为字符串(数据类型)。这就是为什么response.string不起作用。

您可以通过添加这只是告诉:

console.log(typeof response); 

所以不要忘了把:

header('Content-Type: application/json'); 

里面你if块:

而且你对一个错字if块(isset和response):

if (isset ($_POST['func']) && $_POST['func'] === 'genString') { 
    header('Content-Type: application/json'); 
    exit(json_encode(myFunction())); 
} 

在JS错字也:

console.log(response.string); 
       ^^ 
+0

由于头部固定它的语法错误只能从我都键入它。我从来不知道在js typeof感谢 – Dustin

+0

@Dustin当然很高兴这有助于 – Ghost

0

嗯,这是一个语法错误。 请求选项

datatype: 'json' 

应该

dataType: 'json' 
+0

谢谢,这是我忽略了 – Dustin