【问题标题】:Passing variable containing a url to an ajax with cakephp leads to error使用 cakephp 将包含 url 的变量传递给 ajax 会导致错误
【发布时间】:2012-11-15 15:21:52
【问题描述】:

在传递变量时,我的 ajax 代码一切正常,可以说“hello world”,但是当传递包含“hello world http//www.facebook.com”之类的变量时,实际上会导致很多问题。

实际上它是我遇到问题的变量“new_textarea”。 说清楚一点,

var new_textarea = "hello world"; //successfully saves it to database

但是当

var new_textarea = "http://www.facebook.com" // will lead to problems

这是我的 ajax 代码:

$.ajax({
url: '/learns/quickpostcomment/'+user_discussion_id+'/'+user_id+'/'+new_textarea+'/'+parent_id,
success: function(data){
}});

这是我的 cakephp:

public function quickpostcomment()
{
    $post = $this->params['pass'];
    $this->ClassroomComment->create();
    $this->ClassroomComment->set('classroom_id', $post[0]);
    $this->ClassroomComment->set('user_id', $post[1]);
    $this->ClassroomComment->set('comment', $post[2]);
    $this->ClassroomComment->set('parent_id', $post[3]);
    $this->ClassroomComment->save();
    die;
}

到目前为止,我检查的只是触发问题的是变量包含 url 时变量上的“/”或斜杠。

有什么方法可以将包含斜杠或 url 的变量传递给我的 ajax? 我非常需要帮助:(

【问题讨论】:

    标签: php ajax cakephp


    【解决方案1】:

    我认为您应该使用 Ajax 而不是 GET 发送 POST 请求。如果您正确构建发布的数据,您可以在从标准 Cake 表单获取数据时在您的操作中获取它们。

    jQuery.ajax({   
        url     : "<?php echo Router::url(array('controller' => 'learns', 'action' => 'quickpostcomment'), true); ?>,
        type    : "POST",
        cache   : false,
        data    : "data[ClassroomComment][user_discussion_id]=" + user_discussion_id + "&data[ClassroomComment][user_id]=" + user_id + "&data[ClassroomComment][new_textarea]=" + new_textarea + "&data[ClassroomComment][parent_id]=" + parent_id,
        success : function(data){
    
        }
    };
    

    然后发布的数据将在您的控制器中可用:

    $this->request->data['ClassroomComment']
    

    【讨论】:

    • 非常感谢!!!这就是我想出的 $.ajax({ type: "POST", url: '/learns/quickpostcomment/', data: "data[ClassroomComment][user_discussion_id]=" + user_discussion_id + "&data[ClassroomComment][user_id ]=" + user_id + "&data[ClassroomComment][new_textarea]=" + new_textarea + "&data[ClassroomComment][parent_id]=" + parent_id, 成功:function(data){ alert("Okay!"); }跨度>
    【解决方案2】:

    尝试在变量new_textarea 周围使用encodeURIComponent()。有关使用encodeURI()encodeURIComponent 的更多信息,请参阅this answer

    在您的quickpostcomment() 操作中,您可能需要对$post[2] 使用urldecode() 函数。我不记得 cake 是否会自动为您执行此操作,但我怀疑它会这样做。

    【讨论】:

      猜你喜欢
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      相关资源
      最近更新 更多