Javascript 调用 php Web 服务器

Javascript calls to a php webserver

本文关键字:服务器 Web php 调用 Javascript      更新时间:2023-09-26

我的应用程序遇到了一个巨大的问题。我有一个连接到php网络服务的应用程序,当我按下按钮时会获取一些数据。唯一的问题是,我的服务没有响应我,我找不到原因。

我想将"Windesheim"发送到我的服务器,服务器(现在是硬编码(返回"Windesheim"。我没有使用该数组进行测试。我正在使用谷歌浏览器。

这是我.html:

<html>
<head>
    <title>Ekiden</title>
    <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script type="text/javascript" src="_Script.js"></script>       
</head>
<body>
    <input id="team" type="text"/><input id="button" type="button" value="Go" />
    <div id="feedback"></div>
</body>
</html>

这是我.js:

$('#button').click(function() {
var team = $('#team').val();
$.POST('_Dataserver.php', {team: team }, function(data) {
    $('#feedback').text(data);
});
});

这是我.php:

<?php
header('Content-Type: application/json');
$teams = array
(
"Windesheim"=>array
    (
        // Naam, Leeftijd, Tijd, Afstand, Gemiddelde snelheid
        1 => array ('Alfred', 20, 0, 0, 0),
        2 => array ('Willem', 36, 0, 0, 0),
        3 => array ('Michael', 22, 0, 0, 0),
        4 => array ('Stefan', 27, 0, 0, 0),
        5 => array ('Timmy', 20, 0, 0, 0),
        6 => array ('Pascal', 20, 0, 0, 0)
    ),
"Deltion"=>array
    (
        // Naam, Leeftijd, Tijd, Afstand, Gemiddelde snelheid
        1 => array ('Simon', 21, 0, 0, 0),
        2 => array ('Manuel', 33, 0, 0, 0),
        3 => array ('Stephan', 29, 0, 0, 0),
        4 => array ('Marko', 42, 0, 0, 0),
        5 => array ('Nick', 23, 0, 0, 0),
        6 => array ('Achmed', 20, 0, 0, 0)
    ),
"Landstede"=>array
    (
        // Naam, Leeftijd, Tijd, Afstand, Gemiddelde snelheid
        1 => array ('Patrick', 20, 0, 0, 0),
        2 => array ('Mohammed', 18, 0, 0, 0),
        3 => array ('Wilson', 19, 0, 0, 0),
        4 => array ('Walie', 22, 0, 0, 0),
        5 => array ('Marco', 52, 0, 0, 0),
        6 => array ('Mohabie', 45, 0, 0, 0)
    )
);
// Als er teams worden opgevraagd
if (isset($_POST['team'])) 
{
    $team = $_POST['team'];
    if($team == 'Windesheim')
    {
        //echo json_encode($teams[$team]);
        echo json_encode('Windesheim');
    }
}
// Als er niks wordt opgevraagd
else 
{
    echo '';
}
?>
您需要

将_Scripts.js的代码包装在document.ready函数中。

您的代码在 DOM 渲染之前执行,因此$('#button'( 不返回任何元素。

_Scripts.js应该是:

$(document).ready(function() {
    var team = $('#team').val();
    $.POST('_Dataserver.php', {team: team }, function(data) {
        $('#feedback').text(data);
    });
});
$(document).ready(function() {
});

您的 js 代码中缺少上述代码。

在PHP中,您正在尝试从请求/发布值中检查值'Windesheim',

if($team == 'Windesheim') {
    //echo json_encode($teams[$team]);
    echo json_encode('Windesheim');
}

但是在JS中,您将团队ID的值为空,在html输入类型值中为,

<input id="team" type="text"/>

所以它不会从客户端 php 打印/响应任何内容。

要解决,请在 HTML 中将值 '' 更改为 'Windesheim'

(即(<input id="team" type="text" value ="Windesheim"/>