我已经创建了一个REST Web服务,我在其中提取名称和姓氏,然后只返回一条消息,其中包含结果中带有姓名和姓氏的消息。
现在在PhoneGap中,我有以下代码:
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximumscale=1"/>
<link rel="stylesheet" href="css/jquery.mobile.css"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquerym.js"></script>
<script type="text/javascript" src="js/myscript.js"></script>
<script type="text/javascript" charset="utf-8" src="js/cordova-2.3.0.js"></script>
</head>
<body>
<div id ="page1" data-role="page">
<div data-role ="header">
<h1>Welcome to Page 1</h1>
</div>
<a href="#page2" data-transition="flip">Page2</a>
</div>
<div id ="page2" data-role="page">
<div data-role ="header">
<h1>Welcome to Page 2</h1>
</div>
<form>
First name: <input type="text" name="name" id="username"><br>
Last name: <input type="text" name="surname" id="usersurname"><br>
<input type="submit" id ="submit" name="submit" value="GO TIME">
</form>
<a href="#page1" data-transition="flip">Page1</a>
</div>
</body>
</html>
当用户在表单中输入值时,它将运行以下js:
$(document).on('pagebeforeshow','#page2',
function(){
$('#submit').click(function()
{
var name = $("#username").val();
var surname = $("#usersurname").val();
alert(name + " " + surname);
$.post(
"http://localhost/rest/index.php/api/test/name/"+name+"/surname/"+surname+"/format/json",
{'name':name,'surname':surname},
function(data)
{
alert(data.result);
},
"json");
});
});
在我的Codeigniter REST中,我设置了基本URL并具有以下代码:
<?php
require(APPPATH.'/libraries/REST_Controller.php');
class API extends REST_Controller
{
function test_post()
{
$name = $this->post('name');
$surname = $this->post('surname');
$result = "This is working ".$name." ".$surname;
$array = array('result' => $result);
$this->response($array);
}
}
?>
现在,当用户在输入框中输入信息然后单击按钮时,js脚本正常工作,因为出现第一个警报,但由于某种原因,它不会转到codeigniter REST并返回结果,它只是发送我回到第1页。
答案 0 :(得分:2)
你现在可能已经解决了这个问题,但我想我会为你回答这个问题,因为我遇到了类似的问题并偶然发现了这个问题。
基本上,您将无法访问
来自您的模拟器的http://localhost/rest/index.php/api/test/name
,因为您的XAMPP服务器托管在不同的计算机上(模拟器是虚拟机)。例如,通过将请求的URL更改为http://192.168.0.7/rest/index.php/api/test/name
,您可以访问PC上托管的apache服务器。您必须通过打开命令提示符并键入ipconfig
来查找本地IP。您还需要确保您的网络防火墙允许来自端口80的传入流量。
答案 1 :(得分:1)
这不起作用,你不能在phonegap移动应用上使用localhost。
如果您在移动设备上测试此代码,则$ .POST目标不是:
http://localhost/rest/index.php/api/test/name
您的手机与您的PHP服务器有不同的IP地址。
找到您的PHP服务器IP并用它替换localhost。