使用json_encode()将PHP关联数组从函数返回给ajax调用时,应该返回数组而不是对象。

4
这是我的第一篇文章,如果有什么遗漏或者我表达得不够清楚,请见谅。所有的代码都在同一个php文件中。
我的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(response)会记录{"rows":1,"string":"My test string"}而不是一个对象。

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

我以前做过这个,并且已经返回了一个对象,我可以在js中使用response.string。我尝试使用JSON_FORCE_OBJECT,但结果没有影响。


2
你在 repose.string 中有一个拼写错误。 - Dekel
2个回答

3

现在,响应只被视为字符串(数据类型)。这就是为什么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 );
               ^^

谢谢,这个头文件解决了问题。语法错误只是我打字时的问题。我以前不知道JS中有typeof。 - Dustin
@Dustin,很高兴这对你有帮助。 - Kevin

0

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

datatype: 'json' 

应该是

dataType: 'json'

谢谢,这是我忽视的事情。 - Dustin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接