Post方法在Codeigniter中不起作用

时间:2012-06-28 12:18:26

标签: php jquery ajax codeigniter

我正在使用HMVC codeigniter。我想第一次使用jquery ajax。当我使用POST时,它会在使用GET时响应我的数据时给出未定义的错误。

         $.ajax({
          type: "POST",
          url: filelink+"cart/add_cart_item",
          data: {"product_id":id,"quantity":qty,"ajax":"1"},
          dataType: "json",
              success: function(msg){
           alert( "Data Saved: " + msg );
           },
               error: function(jqXHR, textStatus, errorThrown){ 
           alert(textStatus + " " + errorThrown);
            }
      });

google搜索和SO-ing后我到目前为止所尝试的内容

  1. 我的文件网址可以直接访问。我检查了一下。给予回应。

  2. Firebug为同一个文件提供了500个内部服务器错误。

  3. 使用Get正在回复我

  4. 在数据类型中添加了json

  5. 控制器功能

      class Cart extends CI_Controller { // Our Cart class extends the Controller class
    
      function __construct()
         {
        parent::__construct();  
        $this->template->set('controller', $this);
         }
    
      function _remap()
        {
           $uri2 = $this->uri->segment(2);  
           if (is_numeric($uri2) OR $uri2 == FALSE) {
            $this->index(); 
           } else if ($uri2 == 'add_cart_item') {
            $this->add_cart_item();
           } else if ($uri2 == 'show_cart') {
            $this->show_cart();
           }
         }
    
    function add_cart_item(){
          echo "asdfsadfdsf";
          exit; 
        }
      }
    

    任何人都可以帮帮我吗?

4 个答案:

答案 0 :(得分:0)

您的问题可能有原因

您可能正在使用未加载的模型 模型中可能存在一些代码问题 您可能无法从模型中返回任何内容并回复它 此外,如果您需要数据,请使用echo json_encode($ data)

答案 1 :(得分:0)

有时,当您将网站加载为https://example.com时,会出现此问题,但您的ajax调用中的网址为http://example.com

答案 2 :(得分:0)

管理以找到解决方案。问题是由于与FORM一起发送的CI_TOKEN。那是不存在的,并且由于POST方法给出500内部服务器错误。我在我的视图文件中添加了以下内容。

 <?php echo form_open_multipart(); ?>
 <?php echo form_close(); ?>

并使用ajax post请求发送ci_token。

 var ci_token = formObj.find('input[name=ci_token]').val();
 var qty = 1;
 var dataString = 'product_id='+ id + '&quantity=' + qty + '&ajax=' + 1 
 +'&ci_token=' +            ci_token;

这解决了这个问题。我不确定但这被称为CSRF相关的一些问题

谢谢

答案 3 :(得分:0)

你已经使用了_remap函数,在得到$ uri2之后有一个if检查,它检查你在ajax请求中传递的数量变量,它可能有整数值,因为显然可能包含一些整数。

$this->uri->segment();

返回:

product_id=id
quantity=qty
ajax=1

你可以通过调用

取值2
$uri2 = $this->uri->segment(2); 

它将向您返回数量,并且您没有在代码中定义index()函数,这会产生500错误

function _remap()
{
   $uri2 = $this->uri->segment(2);  
   if (is_numeric($uri2) OR $uri2 == FALSE) {
    $this->index(); 
   } else if ($uri2 == 'add_cart_item') {
    $this->add_cart_item();
   } else if ($uri2 == 'show_cart') {
    $this->show_cart();
   }
 }
相关问题