XMLHttpRequest状态始终为0

时间:2019-12-09 01:19:38

标签: javascript json ajax wordpress xmlhttprequest

我正在尝试将来自wordpress.com网站的帖子JSON用于网站的一部分,但是我的请求状态始终返回为0。这是我正在调用的函数:

var wordPress;

var request = new XMLHttpRequest();
request.open("GET", "https://public-api.wordpress.com/rest/v1.1/sites/mywordpresssite.wordpress.com/posts/", true);

request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
    wordPress = JSON.parse(request.responseText);
    return wordPress;
    }
};

1 个答案:

答案 0 :(得分:0)

上面的代码中的链接 https://public-api.wordpress.com/rest/v1.1/sites/mywordpresssite.wordpress.com/posts/

网站{mywordpresssite.wordpress.com}未注册。.

另外,请检查此以获取更多详细信息: https://en.wordpress.com/typo/?subdomain=mywordpresssite

请尝试使用以下代码段作为参考:-

//make request object   
var httpRequest;


//perform click event 
document.getElementById("ajax_json_Btn").addEventListener('click', makeRequest);

// make http request
function makeRequest() 
{
httpRequest = new XMLHttpRequest();

if (!httpRequest) {
alert('Giving up ? Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET','https://public-api.wordpress.com/rest/v1.1/sites/en.blog.wordpress.com/posts/7', true);
httpRequest.send();
}

//handle the http response
function alertContents() 
{
if (httpRequest.readyState === XMLHttpRequest.DONE) 
{
if (httpRequest.status >= 200 && httpRequest.status < 400) {
var myObj = JSON.parse(httpRequest.responseText);
alert(myObj.site_ID);
// alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
}