重定向无法正常工作。 $ .ajax + Cakephp

时间:2014-04-24 04:46:16

标签: php jquery 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 或任何?我还是新手。请帮忙。

2 个答案:

答案 0 :(得分:0)

通过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');
    }            
});

答案 1 :(得分:0)

不确定是什么问题。

但我已经解决了。

$.ajax({
[...]
dataType:'jsonp', //have to be Jsonp because I'm using different domain.
error:function(){
  redirect(url);
}

这样做有点尴尬。但是,我对我无法找到的错误感到沮丧。