我想使用jQuery将一些数据从表单发送到PHP文件。我进行了搜索,发现我必须以JSON形式发送数据并以数组形式接收多个变量。但是我完全感到困惑,这是行不通的。
<input id="username" type="text" class="inputBox">
<input id="password" type="password" class="inputBox">
<button id="submitLogin" class="submitLogin">login</button>
<div id="test"></div>
<div id="test1"></div>
$(document).ready(function() {
$("#submitLogin").click(function() {
var superuser = $("#username").val();
var superpass = $("#password").val();
$.ajax({
type: "POST",
url: 'http://localhost/mainclinic/controllers/login/login.php',
dataType: 'application/json',
data: {
loginid: superuser,
loginpass: superpass
},
cache: false,
success: function(result) {
$('#test').html(result[0]);
$('#test1').html(result[1]);
}
})
})
})
<?php
include "../config.php";
if (!$db)
{
die("Connection failed: " . mysqli_connect_error());
}
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$username = mysqli_real_escape_string($db, $_POST['loginid']);
$password = mysqli_real_escape_string($db, $_POST['loginpass']);
$sql = "SELECT id FROM superusers WHERE docid = '$username' and doccpass = '$password'";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(mysqli_num_rows($result) > 0)
{
$array = array(success, $username);
echo json_encode($array);
}
else
{
$array = array(failed, nousername);
echo json_encode($array);
}
}
?>
答案 0 :(得分:0)
将此部分更改为此:
$.ajax
({
type:"POST",
url:'http://localhost/mainclinic/controllers/login/login.php',
dataType: "json",
data:{loginid:superuser,loginpass:superpass},
cache: false,
success:function (result) {
$('#test').html(result.status);
$('#test1').html(result.result);
}
})
这样的PHP代码:
if(mysqli_num_rows($result) > 0)
{
$array = array('status' => 'success', 'result' => $username);
echo json_encode($array);
}else
{
$array = array('status' => 'failed', 'result' => 'nousername');
echo json_encode($array);
}