用ajax调用php脚本

Calling php script with ajax

本文关键字:脚本 php 调用 ajax      更新时间:2024-07-13

我有一个简单的页面来了解ajax的工作原理,但我无法执行指定的php文件并取得成功。这是代码,额外的解释要点:

html页面:

<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <button onclick="addToDb()">click me!</button>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1./jquery.min.js"></script>
  <script src="js/addtodb.js"></script>
</body>
</html>

js脚本:

function addToDb()
{
    var source = "SoundCloud";
    var partyKey = "4";
    var id = "0987654321";
    //window.alert("check your db"); // this is called as expected
    jQuery.ajax({
        type: 'POST',
        // correctly finds the script but never executes it
        url: 'PHP/functionFilter.php',
        dataType: "json",
        data: {functionname: 'addSong'},
        success: function(response) { window.alert(response); }
    });
};

php文件:

<?php
echo "".$_POST['functionname'];
?>

注意:我没有任何错误。

您使用dataType"json"发送数据。当你回显时,你需要对你的数据进行编码。

$array = array("success" => true, "message" => "hello world");
echo json_encode($array);

问题的累积解决方案

$anArray;
if (isset($_POST['functionname']))
{$anArray = array('message' => $_POST['functionname']);}
else
{$anArray = array('message' => "error");}
echo json_encode($anArray);

在您的php代码上尝试一下

<?php 
    echo json_encode(array(isset($_POST['functionname']) ? $_POST['functionname'] : "error" ));
?>