我在尝试从wordpress中的ajax调用中获取数据时遇到问题。
这是我的代码。
.PHP
<?php
function pfw_get_websites(){
$result[] = array(
"id" => '1',
"title" => 'this is title',
"description" => 'this is the description'
);
echo json_encode($result);
}?>
.HTML:
<div id="app">
<ul>
<li v-for="website in websites">
{{ website }}
</li>
</ul>
</div>
VueJS 和 AJAX 调用:
const app = new Vue({
el:'#app',
data:{
websites: []
},
created(){
var request = {
action: "pfw_get_websites"
};
$.post(user_obj.ajax_url, request).always(function(response){
console.log("This is inside vue" +response);
console.log("This is inside vue" +response.title);
app.websites = response;
});
}
})
我可以验证是否返回了 json,并且我可以看到我在 PHP 中设置的值。 但是,该页面似乎为返回的 json 字符串中的每个字符和字母输出一个列表项。
页面上的输出显示每个列表项在 json 字符串中只有一个字符。 Response.title 以未定义的形式出现。 我在这里错过了什么?
你需要将 PHP 返回的字符串解析为 JSON。
添加以下行
$.post(user_obj.ajax_url, request).always(function(response){
response = JSON.parse(response); // Add this line
console.log("This is inside vue" +response[0]);
console.log("This is inside vue" +response[0].title);
app.websites = response;
});