[英]Redirect not working. $.ajax + Cakephp
美好的一天。
我有一个我无法解决的问题,我正在使用Cakephp和$.ajax
。 $.ajax
的数据可以传递到我的数据库中。 但是问题是成功后我无法重定向到另一个页面。
我已经尝试过if($save){ echo something}
并正在工作,只是$this->redirect
部分。
Cakephp代码如下:
public function testingadd() {
$this->layout=null;
$name = $_GET['name'];
$email = $_GET['email'];
$phone = $_GET['phone'];
$this->Newlead->create();
$this->Newlead->set("name",$name);
$this->Newlead->set("email",$email);
$this->Newlead->set("phone",$phone);
$save = $this->Newlead->save();
if($save)
{
$this->redirect('/Newlead/thankyou');
}
}
Ajax代码如下:
$("#btn-submit").click(function ()
{
var obj = new Object();
obj.n = $("#inputName").val();
obj.e = $("#inputEmail").val();
obj.c = $("#inputMobile").val();
$.ajax({
type: 'POST',
url: '/Newleads/testingadd.json',
data: {
'name' : obj.n,
'email' : obj.e,
'phone' : obj.c
},
dataType: "jsonp",
timeout:1000,
jsonp:'jsonp'
});
});
是否有更多的代码需要被添加到CakePHP的任何文件,如routes.php文件 ,PagesController.php或任何? 我还是这个新手。 请帮忙。
通过JavaScript在客户端上重定向,具体取决于您的服务器响应:
服务器上的代码(控制器)
public function testingadd()
{
[...]
if($save)
{
return json_encode(array('saveSuccess' => true));
}
}
客户代码
$.ajax({
[...],
dataType: 'json',
success: function(data) {
if(data.saveSuccess === 'true')
{
// the redirect
window.location = '/Newlead/thankyou';
}
},
error: function()
{
alert('an error occured');
}
});
不确定是什么问题。
但是我已经解决了。
$.ajax({
[...]
dataType:'jsonp', //have to be Jsonp because I'm using different domain.
error:function(){
redirect(url);
}
这样做有点尴尬。 但是,我为找不到的错误感到沮丧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.