无法在Javascript/jQuery中读取AJAX调用中的Json对象
背景:我正在处理一个PHP-MVC web项目,在主页中,我试图获得一个界面,在该界面中,会显示页面加载新闻提要。 提供了一个文本框,我们可以在其中输入文本,这将作为最新的提要,并通过AJAX的帮助持久化到DB 该界面看起来类似于twitter WEB 问题:现在,为了保持这一目标,我编写了以下Js和controller文件。 我面临的问题是JS中接收到的对象/变量无法在Javascript/jQuery中读取AJAX调用中的Json对象,javascript,php,jquery,ajax,json,Javascript,Php,Jquery,Ajax,Json,背景:我正在处理一个PHP-MVC web项目,在主页中,我试图获得一个界面,在该界面中,会显示页面加载新闻提要。 提供了一个文本框,我们可以在其中输入文本,这将作为最新的提要,并通过AJAX的帮助持久化到DB 该界面看起来类似于twitter WEB 问题:现在,为了保持这一目标,我编写了以下Js和controller文件。 我面临的问题是JS中接收到的对象/变量latestComment的类型为String,但在解析接收到的对象后,我无法检索到内容(显示未定义) Index.js $
latestComment
的类型为String,但在解析接收到的对象后,我无法检索到内容(显示未定义)
Index.js
$(function() {
if ($('#comment_button').length !== 0) {
/ / On click of comment_button, newfeed
//identifier data is sent to controller
//'newfeed' is binded with a input type='text' in html
//controller handles with postFeed($param) and persists data into DB
//the return value from method is Json encoded Object to controller
$('#comment_button').on('click', function() {
var stringValue = $('#newfeed').val();
//check if input data is not null
if (stringValue) {
$.ajax(url + "/home / postFeed / " + stringValue)
.done(function(latestComment) {
//but the recieved object 'latestComment' is of type string
obj = jQuery.parseJSON(latestComment);
$('#ajax-result-box').html('');
var Str = '';
$.each(obj, function(index, inVal) {
Str += '<div class="jumbotron">Author:' + obj.author + '</div>';
});
$('#ajax-result-box').html(Str);
})
.fail(function() {
// this will be executed if the ajax-call had failed
})
.always(function() {
// this will ALWAYS be executed, regardless if the ajax-call was success or not
});
}
//if input data is null
else
alert("
Input Empty!!");
});
}
});
您是说
obj
是否未定义?我认为这根本不可能。或者你是说作者是未定义的?这更有可能,因为你的循环很奇怪。您正在迭代obj
,但没有对循环变量执行任何操作。也许你真的想要inVal.author
?obj
的值是多少?使用json响应更新。JSON响应将始终是一个字符串。这就是为什么要使用jQuery.parseJSON(latestComment)将其转换为对象代码>旁注,如果您的服务器没有设置标题内容类型:application/json
,请将数据类型:“json”
添加到ajax请求中。@FelixKling您是对的。ranjzz您实际上需要inVal.author的值,而不是obj.author的值。php函数的输出是什么?你能在obj=…
上方添加一个console.log(latestComment)
并显示结果吗?@FelixKling谢谢你指出,我犯了这么一个愚蠢的错误,现在它工作了……我用$中的inVal替换了obj。每条语句::-)
public function postFeed($postFeedVal)
{
//'postFeedVal' is the recieved input value from js file
//Load Model and call its method,return json encoded 'latestcomment'
//to javascript
$feed_model = $this->loadModel('FeedModel');
$feed_model->addFeeds($postFeedVal);
$latestComment=$feed_model->getLastFeed();
echo json_encode($latestComment);
}