简体   繁体   English

从Java脚本调用PHP Web服务

[英]Calling PHP webservice from Java script

I am new to PHP and Javascript Development , I am trying to execute this code but it fails 我是PHP和Javascript开发的新手,我正在尝试执行此代码,但失败

<?php
if(isset($_POST['username']) and isset($_POST['password'])) {

 // do logic for logining in (usually query your db)
if ($_POST['username'] == 'test' && $_POST['password'] == 'test') {
$data['success'] = true;
$data['message'] = 'Login succesful';
} else {
$data['success'] = false;
$data['message'] = 'Login failed';
}
// return json
echo json_encode($data);

}
?>

here is the Javascript file 这是Javascript文件

<script>
    $(document).ready(function() {
    alert("dddd");
        $('#loginForm').submit(function() {
            $('#output').html('Connecting....');
            var postTo = 'http://localhost/Login/login.php';
            alert(postTo);
            $.post(postTo,{username: $('[name=username]').val() ,   password: $('[name=password]').val()} , 
                function(data) {

                    if(data.message) {
                        alert(data);
                    } else {
                        $('#output').html('Could not connect');
                    }

                },'json');

            return false;
        });
    });
</script>

Please help , Thanking you in Advance ! 请帮助,在此先感谢您!

Assuming $data wasn't defined anywhere, this should fix it: 假设没有在任何地方定义$data ,这应该可以解决:

<?php
    $data = Array();
    if(isset($_POST['username']) and isset($_POST['password'])) {

         // do logic for logining in (usually query your db)
        if ($_POST['username'] == 'test' && $_POST['password'] == 'test') {
        $data['success'] = true;
        $data['message'] = 'Login succesful';
    } else {
        $data['success'] = false;
        $data['message'] = 'Login failed';
    }
    // return json
    echo json_encode($data);

    }
?>
if(isset($_POST['username']) and isset($_POST['password'])) {

should be 应该

if(isset($_POST['username']) && isset($_POST['password'])) {

as a first correction. 作为第一次更正。

Install Firefox with Firebug extension, Open it using F12, Enable the 'NET', 'SCRIPT' and 'CONSOLE' tabs. 安装具有Firebug扩展名的Firefox,使用F12打开它,启用“ NET”,“ SCRIPT”和“ CONSOLE”选项卡。 Put a breakpoint in the script (around the alert(postTo)) using the SCRIPT tab. 使用SCRIPT选项卡在脚本中(在alert(postTo)附近)放置一个断点。 Refresh the page and step through it, monitoring the console. 刷新页面并逐步浏览,监视控制台。 Use the NET tab to check that both the request and response of the php script is correct. 使用NET选项卡检查php脚本的请求和响应是否正确。

The code above works in my environment, (with the slight change of alert(data) to alert(data.message)). 上面的代码在我的环境中有效((将alert(data)略微更改为alert(data.message)))。 The following works for me: 以下对我有用:

login.php: login.php中:

<?
if(isset($_POST['username']) and isset($_POST['password'])) {
// do logic for logining in (usually query your db)
if ($_POST['username'] == 'test' && $_POST['password'] == 'test') {
$data['success'] = true;
$data['message'] = 'Login succesful';
} else {
$data['success'] = false;
$data['message'] = 'Login failed';
}
// return json
echo json_encode($data);

}
?>

login.html: 的login.html:

<head>
<script type='text/javascript' src='jq/jquery.js'></script>

<script type='text/javascript'>
    $(document).ready(function() {
        alert("dddd");
        $('#loginForm').submit(function() {
            $('#output').html('Connecting....');
            var postTo = 'http://localhost/login.php';
            alert(postTo);
            $.post(postTo,{username: $('[name=username]').val() ,   password: $('[name=password]').val()} , 
                function(data) {

                    if(data.message) {
                        alert(data.message);
                    } else {
                        $('#output').html('Could not connect');
                    }

                },'json');

            return false;
        });
    });
</script>
</head>

<body>
<form id='loginForm'>
  <input type='text' id='username' name='username'/>
  <input type='text' id='password' name='password'/>
  <button type='submit'>Submit</button>
</form>
</body>

Funnily enough it works for me in Firefox. 有趣的是,它在Firefox中对我有效。 I had the problem with IE a while back and the solution was to add the correct headers to the top of the php script: 我有一阵子与IE的问题,解决方案是将正确的标头添加到php脚本的顶部:

<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
...

EDIT: Reproduced it by calling it from another machine. 编辑:通过从另一台计算机调用它来重现它。 try to change var postTo = 'http://localhost/test/test.php'; 尝试更改var postTo = 'http://localhost/test/test.php'; to var postTo = 'test/test.php'; var postTo = 'test/test.php'; .

here's what I tested with ( I woud recommend you use firebug and console.log() instead of alert()): 这是我测试过的(我建议您使用firebug和console.log()而不是alert()):

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
 $('#output').html('somestuff');

    $('#loginForm').submit(function() {
        $('#output').html('Connecting....');
        var postTo = 'http://localhost/test/test.php';
        //alert(postTo);
        $.post(postTo,{username: $('[name=username]').val() ,   password:  $('[name=password]').val()} , 
            function(data) {

                if(data.message) {
                   //  console.log(data);
                    $('#output').html('Ya got it: '+ data.message);
                } else {
                    $('#output').html('Could not connect');
                }

            },'json');

        return false;
    });
});
</script>
</head>

<body>
<form id="loginForm">
    <input type="text" name="username" value="test"/>
    <input type="text" name="password" value="test"/>
    <input type="submit"  />
</form>
<div id="output"></div>
</body>

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

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