gpt4 book ai didi

JQuery 和 Ajax : Cannot read property 'length' of undefined

转载 作者:行者123 更新时间:2023-12-03 23:03:43 24 4
gpt4 key购买 nike

我试图通过使用 URL 中的变量和 AJAX 来显示 JSON,从网站获取特定请求。似乎一切正常,但出现错误“TypeError:无法读取未定义的属性‘长度’”。调试器指向 JQuery 文件和我的脚本中的行 ($.ajax.success)。

function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}

$(document).ready(function () {

var output = $('#news');
var postid = getQueryVariable('id');

$.ajax({
url: 'http://www.domain.pro/api/get_post/?post_id=' + postid + '&post_type=news',
async: false,
callback: 'callback',
crossDomain: true,
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'jsonp',
timeout: 5000,
success: function (data, status) {
$.each(data.posts, function (i, item) {
var news = '<div>' + item.title + '</div><div>' + item.content + '</div><hr/>';

output.append(news);


});
},
error: function () {
output.text('There was an error loading the data.');
}
});
})

你能帮我解决这个问题吗?非常感谢您的帮助。

最佳答案

您应该在对其执行操作之前验证数据:

已更新

 $.ajax({
url: 'http://www.domain.pro/api/get_post/?post_id=' + postid + '&post_type=news',
async: false,
callback: 'callback',
crossDomain: true,
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'jsonp',
timeout: 5000,
success: function (data, status) {
if(data != undefined && data.post != undefined){
$('#news').append('<div>' + data.post.title + '</div><div>' + data.post.content + '</div><hr/>');
}
},
error: function () {
output.html('<h1 class="error">There was an error loading the data.</h2>');
}
});

关于JQuery 和 Ajax : Cannot read property 'length' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14199949/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com