gpt4 book ai didi

javascript - 使用 ajax 将数据发布到 PHP 文件

转载 作者:行者123 更新时间:2023-11-30 17:20:57 24 4
gpt4 key购买 nike

我正在通过对 php 文件的 $.ajax 调用来发布数据。 ajax 调用完成后,我运行另一个 javascript 函数,该函数在 php 文件上执行 $.getJSON。

在 php 文件中有一个变量,它应该具有来自 ajax 的已发布数据的值,但它是空的。

function inputSummonerName() {
inputName = prompt("summoners name");

$.ajax({
type: 'POST',
url: 'ajax.php',
data: { n : inputName },
complete: function() {
getImageData();
}
});
}

function getImageData() {
$.getJSON('ajax.php', function (json) {
if(!json){
console.log("empty");
}
else{
$.each(json, function (index) {
summonerProfileIconId = json[index].profileIconId;
summonerName = json[index].name;
summonerLevel = json[index].summonerLevel;
$(".summonerName").text(summonerName);
$(".summonerProfileIconId").attr("src", "http://ddragon.leagueoflegends.com/cdn/4.13.1/img/profileicon/" + summonerProfileIconId + ".png");
$(".summonerLevel").text("Level" + summonerLevel);
});
}
});
}

这是 php 文件 ajax.php:

<?php
$apikey = "...";
if (isset($_POST["n"])) {
$summonerName = $_POST["n"];
}

$data = json_decode(file_get_contents("https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/" . $summonerName . "?api_key=" . $apikey ));

echo json_encode($data);

...
?>

最佳答案

您正在向 PHP 文件发出两个请求。

  1. $.ajax - 从远程服务器获取你想要的数据并返回它。
  2. $.getJSON - 再次访问远程服务器(但缺少名称)并返回它。

您正在尝试从 2 获取数据,但数据不存在。不要使用 getJSON。只需在您的第一个 complete 函数中使用数据。更好的做法是使用 success,这样您就不会在服务器出现错误时尝试使用它。也可以考虑添加显式的 error 处理程序。

您还应该编写 PHP,以便它告诉浏览器它正在发送 JSON 而不是 HTML,解码 JSON 然后除了重新编码之外什么都不做是没有意义的。

这样的:

header("Content-Type: application/json");
echo file_get_contents("https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/" . $summonerName . "?api_key=" . $apikey );

然后在 JS 中:

function inputSummonerName() {
inputName = prompt("summoners name");
$.ajax({
type: "POST",
url: "ajax.php",
data: {
n: inputName
},
success: function(a) {
if (!a) console.log("empty"); else $.each(a, function(b) {
summonerProfileIconId = a[b].profileIconId;
summonerName = a[b].name;
summonerLevel = a[b].summonerLevel;
$(".summonerName").text(summonerName);
$(".summonerProfileIconId").attr("src", "http://ddragon.leagueoflegends.com/cdn/4.13.1/img/profileicon/" + summonerProfileIconId + ".png");
$(".summonerLevel").text("Level" + summonerLevel);
});
}
});
}

关于javascript - 使用 ajax 将数据发布到 PHP 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25141078/

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