0

我是使用 ajax 的新手,在发布变量和访问控制器中的这些变量时遇到了麻烦。

这是控制器代码

class autocomplete extends CI_Controller {
  // just returns time
  function workdammit()
  {
    $product = $this->input->post('productName');
/*      $this->load->model('product_model');
    $q = 'SELECT quantity FROM products WHERE productName = "BC20BA"';
    $data = $this->product_model->get_record_specific($q);

    echo json_encode($data[0]->quantity);
*/
    echo $product;

  }

  function index()
  {
    $this->load->view('autocomplete_view');
  } 
}

如果我将 更改为echo这样的单引号内的字符串'Hello World',它将正确地将hello world返回到视图。但是如果我像现在这样尝试它,它不会做同样的事情。此外,如果我使用echo json_encode($product);它,则返回 false。

这是使用ajax查看代码。

$( document ).ready(function () {
  // set an on click on the button
  $('#button').click(function () {
        $.ajax({
    type: "POST",
    url: "<?php echo site_url('autocomplete/workdammit'); ?>",
    dataType: "json",
    data: 'productName',
    success: function(msg){  
        alert(msg);

    }
    });
  });
});
</script>
</head>
<body>
  <h1> Get Data from Server over Ajax </h1>

 <br/>
  <button id="button">
     Get posted varialbe
 </button>
4

1 回答 1

1
class autocomplete extends CI_Controller {
// just returns time
    function workdammit()
    {
        $product = $this->input->post('productName');
        //echo $product;
        //in ajax dataType is json -here You have to return json data
        echo json_encode($product);
    }
...
}    

//javascript file
var productName = $('#productName).val();//get value of product name from form

$('#button').click(function () {
    $.ajax({
    type: "POST",
    url: "<?php echo site_url('autocomplete/workdammit'); ?>",
    dataType: "json",
    data: {productName:productName},//You have to send some data from form
    success: function(msg){  
        alert(msg);

    }
});
于 2013-08-31T22:07:21.870 回答