1

我正在尝试为我的 PhoneGap 应用程序制作一个简单的登录表单。由于 PhoneGap 不能在客户端使用任何 PHP,我必须使用 AJAX 将数据发送到服务器。我找到了一个简单的 PHP 登录教程,但我真的不知道如何让它与 ajax 一起使用。

我知道如何将值发布到 PHP 文件,但是如果用户名和密码正确,我如何将用户重定向到页面,或者如果信息无效,如何拒绝他们进入网站?

这是我现在拥有的代码:

JS

jQuery.ajax({ 
    type: "POST", 
    url: serviceURL + "login.php", 
    data: 'username='+username+'&password='+password,  
    cache: false,
        }

登录.php

<?php
include 'config.php';

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['username'];
$mypassword=$_POST['password'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$sql="SELECT * FROM users WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1){
//  redirect 
header("location:settings.html");
}
else {
echo "Wrong Username or Password";
}
?>

那么我怎样才能使if($count==1){....部分对我的应用程序采取行动

4

1 回答 1

1

首先,您必须设置要检索的预期数据类型(例如 html)。之后,您还必须在成功检索数据后对检索到的数据指定一个函数...

像这样的东西:

jQuery.ajax({ 
    type: "POST", 
    success: function(data) { // After retrieving the data from the php-file
    alert(data);}
    url: serviceURL + "login.php", 
    data: 'username='+username+'&password='+password,  
    cache: false,
    dataType:'html' // Expected return data type...
}

The data Variable contains the return string from the php file, so you have to echo something out with the php script, like "logged in" and then you have to filter / check this string with javascript...

Lucian

于 2012-05-31T09:41:07.687 回答