dongsou0083 2015-08-23 23:11
浏览 68
已采纳

codeigniter或PHP - 如何在特定的AJAX POST提交后转到URL

I am successfully inserting data into my database in codeigniter via a an ajax post from javascript:

//JAVASCRIPT:

$.ajax({
   type: "POST",
   url: submissionURL,
   data: submissionString,
   failure: function(errMsg) {
        console.error("error:",errMsg);
   },
   success: function(data){
        $('body').append(data); //MH - want to avoid this
   }
});

//PHP:
public function respond(){
    $this->load->model('scenarios_model');
    $responseID = $this->scenarios_model->insert_response();
    //redirect('/pages/view/name/$responseID') //MH - not working, so I have to do this
    $redirectURL = base_url() . 'pages/view/name/' . $responseID;
    echo "<script>window.location = '$redirectURL'</script>";
}

But the problem is that I can't get codeigniter's redirect function to work, nor can I get PHP's header location method to work, as mentioned here:

Redirect to specified URL on PHP script completion?

either - I'm guessing this is because the headers are already sent? So as you can see, in order to get this to work, I have to echo out a script tag and dynamically insert it into the DOM, which seems janky. How do I do this properly?

  • 写回答

2条回答 默认 最新

  • douxing1969 2015-08-23 23:19
    关注

    Maybe you can 'return' the url in respond function and use it in js
    PHP :

    public function respond(){
        // code
        $redirectURL = base_url() . 'pages/view/name/' . $responseID;
        return json_encode(['url' => $redirectURL]);
    }
    


    JS :

    $.ajax({
       type: "POST",
       url: submissionURL,
       data: submissionString,
       dataType: 'JSON',
       failure: function(errMsg) {
            console.error("error:",errMsg);
       },
       success: function(data){
          window.location = data.url
       }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答