如何从 jQuery 调用时获取 php 函数的返回值


How to get the return value of a php function when calling from jQuery?

我有一个php函数返回一个字符串值,该值将放入html文件中。

function getDirectionInfo($routeNumber) {
    //some code here
    $dirinfo = "<p> some text </p>";
    return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
    getDirectionInfo($_POST['getDirectionInfo']);
}

所以在jQuery中,我有一个以下函数

$(".onebtn").click(function(){
    $("#directioninfo").empty();
    var routeNumber = $(this).text();
    $.ajax({
        url: "./systemView_Function.php",
        type: "POST",
        data: {"getDirectionInfo": routeNumber},
        success: function(data) {   
            console.log("HIHIHIHI");
            $("#directioninfo").append(data);
        }
    });
})

现在控制台.log打印"HIHIHIHIHI",但jQuery不会将数据附加到html中。有谁知道如何在从jQuery调用时获取php函数的返回值?

而不是返回使用:

echo json_encode($dirinfo);
die;

dataType字段添加到设置为 json$.ajax()函数参数中也是个好主意,以确保成功函数中的数据将被正确解析。

  1. 您只需要使用echo发送回响应

  2. 使用 var routeNumber = $(this).val(); 获取按钮值

.PHP:

<?php
function getDirectionInfo($routeNumber) {
    //some code here
    $dirinfo = "<p> routeNumber". $routeNumber." </p>";
    return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
    echo getDirectionInfo($_POST['getDirectionInfo']);
}else{
    echo "not set";
}

AJAX & HTML

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
	$(".onebtn").click(function(){
		$("#directioninfo").empty();
		var routeNumber = $(this).val();
		console.log("routeNumber = " + routeNumber);
		$.ajax({
			url: "systemView_Function.php",
			type: "POST",
			data: {"getDirectionInfo": routeNumber},
			success: function(data) {   
				console.log("data = " + data);
				$("#directioninfo").append(data);
			}
		});
	})
});
</script>
</head>
<body>
	<div id="directioninfo"></div>
	<input type="button" value="12346" class="onebtn" />
</body>
</html>

谢谢大家。我刚刚发现我在jQuery中犯了一个非常愚蠢的错误。我应该使用 var routeNumber = parseInt($(this).text()); 而不是 var routeNumber = $(this).text(); 因此,以下代码用于在从 jQuery 调用时获取 php 函数的返回值。

在 PHP 中

function getDirectionInfo($routeNumber) {
    //some code here
    $dirinfo = "<p> some text </p>";
    echo json_encode($dirinfo);
}
if (isset($_POST['getDirectionInfo'])) {
    getDirectionInfo($_POST['getDirectionInfo']);
}

在 jQuery 中

$(".onebtn").click(function(){
    $("#directioninfo").empty();
    var routeNumber = parseInt($(this).text());
    $.ajax({
        url: "./systemView_Function.php",
        type: "POST",
        data: {"getDirectionInfo": routeNumber},
        dataType: "JSON",
        success: function(data) {   
            $("#directioninfo").append(data);
        }
    });
})