【发布时间】:2016-01-08 00:25:52
【问题描述】:
我有一个 JQM 移动应用程序,它使用 Slim 框架与 REST Api 交互,在 localhost 上测试它一切正常,但是当我将 API 上传到我的 Web 服务器时,只有使用 GET 的页面连接到服务器,所有 POST请求无法连接到服务器。代码如下
Index.html 页面
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My Mobile APP</title>
<link rel="stylesheet" href="themes/itfjobportal.min.css" />
<link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="css/jquery.mobile.structure-1.4.5.min.css" />
<link rel="stylesheet" href="themes/custom.css" />
<script src="js/jquery-2.1.3.min.js"></script>
<script>
$(document).bind("mobileinit", function()
{
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;
});
</script>
<script src="js/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page" data-theme="a">
<div data-role="header" data-position="inline">
<h1> Login Page</h1>
</div>
<div data-role="content" data-theme="a" class="login-container">
<form action="" method="post" name="admin" id="admin">
<div id="failedLogin"></div>
<label for="username">Username</label>
<input name="username" type="text" id="username" value="">
<label for="password">Password</label>
<input name="password" type="password" id="password" value="">
<div id="lower">
<input type="submit" name="submit" id="submitbutton" value="Login" data-role="button" data-inline="true" data-theme="b" data-icon="lock">
</div>
</form>
</div>
</div>
</body>
</html>
<script src="js/ajaxGetPost.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on("click",'#submitbutton',function() {
var username=$('#username').val();
var password=$('#password').val();
if (username=='') {
alert("Please enter username");
$('#username').focus();
return false;
}
if (password=='') {
alert("Please enter password");
$('#password').focus();
return false;
}
encode=JSON.stringify({'username': username, 'password': password});
var url = 'http://mywebsite.com/api/doLogin';
post_data(url,encode, function(data)
{
if(data.status == 'failed') {
$("#failedLogin").html('Supplied credentials are invalid');
} else {
//alert(JSON.stringify(data));
location.href = 'index.php';
}
});
return false;
});
});
</script>
</code>
我的 ajaxGetPost.js
function post_data(url,encodedata, success)
{
$.ajax({
type:"POST",
url:url,
crossDomain: true,
data :encodedata,
dataType:"jsonp",
restful:true,
contentType: 'application/json',
cache:false,
timeout:20000,
async:true,
beforeSend :function(data) { $.mobile.loading('show', {theme:"b", text:"LOADING... Please Wait...", textonly:true, textVisible: true}); },
complete: function() {$.mobile.loading('hide');},
success:function(data){
// alert(data);
},
error:function(data){
// alert(JSON.stringify(data));
alert("Error Sending Data");
}
});
}
function get_data(type,url, success)
{
$.ajax({
type:type,
url:url,
dataType:"json",
restful:true,
cache:false,
timeout:20000,
async:true,
beforeSend :function(data) { $.mobile.loading('show') },
complete: function() {$.mobile.loading('hide') },
success:function(data){
success.call(this, data);
},
error:function(data){
alert("Error Retrieving Data");
}
});
}
下面是服务器上的index.php
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');
require 'dbConfig.php';
require 'Slim/Slim.php';
//include('../lib/config.php');
\Slim\Slim::registerAutoloader();
$slim_app = new \Slim\Slim();
$slim_app->post('/doLogin','doLogin');
$slim_app->get('/loadJobs','loadJobs');
$slim_app->post('/applyJob','applyJob');
$slim_app->post('/newUser','newUser');
$slim_app->post('/editUser','editUser');
$slim_app->get('/loadEditUser/:eid','loadEditUser');
$slim_app->get('/deleteUser/:did','deleteUser');
$slim_app->run();
function doLogin() {
$request = \Slim\Slim::getInstance()->request();
$update = json_decode($request->getBody());
try {
$db = getDB();
$stmt = $db->prepare("SELECT * FROM job_seeker where username=:username1 AND pwd=:password1 AND status=1");
$stmt->bindValue(':username1', $update->username, PDO::PARAM_INT);
$stmt->bindValue(':password1', $update->password, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetch(PDO::FETCH_ASSOC);
$db = null;
if(count($rows)) {
echo '{"status": "success"}';
}
else {
echo '{"status": "failed"}';}
} catch(PDOException $e) {
echo '{"error":{"msg":'. $e->getMessage() .'}}';
}
}
我也有一个 .htaccess 文件,如您所见,我已经在 htaccess 中添加了标题添加 Access-Control-Allow-Origin "*" 但我仍然将它放在 index.php 文件中以防万一没有正确重定向
<IfModule mod_rewrite.c>
RewriteEngine On
# RewriteBase /
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>
【问题讨论】:
标签: php jquery .htaccess rest jquery-mobile