简体   繁体   English

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

[英]Use ajax post data to a PHP file

I'm posting data through an $.ajax call to a php file. 我通过$ .ajax调用将数据发布到php文件。 When the ajax call is completed, I run another javascript function that does a $.getJSON on the php file. 当ajax调用完成后,我运行了另一个在PHP文件上执行$ .getJSON的javascript函数。

In the php file is a variable that should have the value of the posted data from ajax, but it is empty. 在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);
            });
        }
    });
}

here is the php file ajax.php: 这是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);

    ...
?>

You are making two requests to the PHP file. 您正在向PHP文件发出两个请求。

  1. $.ajax - gets the data you want from the remote server and returns it. $.ajax从远程服务器获取所需的数据并返回。
  2. $.getJSON - hits the remote server again (but with the name missing ) and returns that. $.getJSON再次命中远程服务器(但名称丢失 )并返回。

You are trying to get the data from 2, where it doesn't exist. 您正在尝试从不存在的2中获取数据。 Don't use getJSON . 不要使用getJSON Just use the data in your first complete function. 只需在第一个complete功能中使用数据即可。 Better, use success so that you don't try using it in the event of a server error. 更好的是,使用success这样就不会在服务器出错时尝试使用它。 Consider adding an explicit error handler too. 也考虑添加显式error处理程序。

You should also write the PHP so it tells the browser it is sending JSON instead of HTML, and there is no point in decoding the JSON and then doing nothing but reencoding it. 您还应该编写PHP,以便它告诉浏览器它正在发送JSON而不是HTML,并且对JSON进行解码然后再重新编码就没有任何意义。

such: 这样:

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 );

Then in the JS: 然后在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);
            });
        }
    });
}

You are calling the script twice by using $.ajax ánd $.getJSON (which is a wrapper for $.ajax). 您通过使用$ .ajax和$ .getJSON(这是$ .ajax的包装)两次调用脚本。 Solution: 解:

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

    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: { n : inputName},
        success: function(data, textStatus, jqXHR)
        {
            getImageData($.parseJSON(data));
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //handle your error!
        }
    });

}

function getImageData(data)
{
    $.each(data, function (index) 
    {
        summonerProfileIconId = data[index].profileIconId;
        summonerName = data[index].name;
        summonerLevel = data[index].summonerLevel;
        $(".summonerName").text(summonerName);
        $(".summonerProfileIconId").attr("src", "http://ddragon.leagueoflegends.com/cdn/4.13.1/img/profileicon/" + summonerProfileIconId + ".png");
        $(".summonerLevel").text("Level" + summonerLevel);
    });
}

I also changed complete to success / error, so that on an error the other functions won't get angry because of the non array value. 我也将完成更改为成功/错误,因此在发生错误时,其他功能也不会因为非数组值而生气。

try putting the n in quotes it should be a key, not a variable. 尝试将n放在引号中,它应该是键,而不是变量。 IE: IE:

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

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

PS: Also there is a short hand for jquery if you really want http://api.jquery.com/jQuery.post/ PS:如果您真的想要http://api.jquery.com/jQuery.post/,也可以使用jquery的捷径

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM