gpt4 book ai didi

javascript - REST API,从 PHP 返回 JSON 对象到 JS 文件

转载 作者:行者123 更新时间:2023-11-28 00:20:53 25 4
gpt4 key购买 nike

我是第一次编写某种 REST API,所以我需要一些帮助。我在 stackoverflow 上找到了一些针对我的问题的解决方案,并且我设法解决了它们。但现在我又找了一个,找不到解决办法。

首先是js文件代码。

$.getJSON('test.php', function(data) {
console.log(data);
articles = data;
return articles;
});

这是js文件,我从中向php文件发送请求,然后获取数据。问题是,当我记录它时,我从 php 返回的数据在浏览器控制台中看起来很好,所有数据都在那里。但是当我尝试在页面上使用该数据(通过我的 return 语句)时,它不起作用。如果我将返回文章行替换为

return [{"name":'Name goes here',"description":'Description goes here'}];

它在页面上运行良好。这让我很困扰,因为在浏览器控制台中我可以看到从 php 文件返回的所有对象,但它们在页面上不起作用。我希望你们中的任何人都可以帮助我。我正在下面粘贴我的 php 文件。

$json = array(
array(
"name" => 'Name goes here',
"description" => 'Test description.',
"link" => 'articles/articleName',
"img" => '../images/article1.jpg'
),
array(
"name" => 'Name goes here 2',
"description" => 'Not ready yet',
"link" => '#',
"img" => ''
),
array(
"name" => 'Name goes here 3',
"description" => 'Not ready yet',
"link" => '#',
"img" => ''
)
);

$jsonstring = json_encode($json, JSON_PRETTY_PRINT);
echo $jsonstring;

最佳答案

问题是您在 $.getJson 调用的异步部分中返回。

你拥有什么:

function myFunction()
{
$.getJSON('test.php', function(data) {
console.log(data);
articles = data;
return articles;
});
}
var articles = myFunction();

myFunction 运行,并且不返回任何内容,然后 $.getJSON 获取其响应,并且与它没有任何关系。返回在那里没有多大意义,因为代码已经“继续前进”

您需要做的是处理 getJSON 异步部分内的数据(或传入一个函数来在其中执行操作)

您需要什么:

function myFunction()
{
$.getJSON('test.php', function(data) {
console.log(data);
articles = data;

//do something with articles
//maybe set a div equal to them
$("#myArticles").innerHTML = articles;

//or call a function with articles as a param
doSomethingCool(articles);
});
}

function doSomethingCool(arts)
{
alert("You have articles: " + arts);
}

你甚至可以将你想要做的事情作为参数传递

function myFunction(callback)
{
$.getJSON('test.php', function(data) {
console.log(data);
articles = data;

callback(articles);
});
}


myfunction(alert); //will alert with the articles

//define the callback function 'on the fly'
myfunction(function(articlesFromJson) {
if(articlesFromJson.length > 2)
alert("wow 2+ arcticles");
});

上面的代码会抓取文章两次,并且每次都会做不同的事情。

关于javascript - REST API,从 PHP 返回 JSON 对象到 JS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30036700/

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