简体   繁体   English

CodeIgniter中的AJAX调用未按预期工作

[英]AJAX call in CodeIgniter not working as expected

I have an ajax call from my javascript file that is attempting to post data to a specific function in my controller. 我的javascript文件有一个Ajax调用,试图将数据发布到控制器中的特定功能。 When I view the data in the success function of my call, I get the html of a totally unrelated view as the returned data, and I am unsure why. 当我在调用的成功函数中查看数据时,我得到了一个完全不相关的视图的html作为返回的数据,但我不确定为什么。

My AJAX call: 我的AJAX电话:

function processResults(task_id){
  var finalResults = localStorage.getItem('results');
  console.log(finalResults);

  $.ajax({
    type: 'POST',
    url: 'task/getResults',
    data: {'answers': finalResults},
    success: function(data){
      console.log(data);
    }
 });
} 

My Controller function: 我的控制器功能:

public function getResults(){

  $this->load->model('testResults');

  $finalResults = $this->input->post('answers');

  $finalResults = json_decode($finalResults, true);

  if ($taskTestId != '') {
    $this->testAnswers->insertTaskData($finalResults);
  }
}

Is the url in the ajax call incorrect? ajax调用中的网址不正确吗? I'm not really sure why it is outputting the html of a completely unrelated view. 我不太确定为什么要输出完全不相关的视图的html。 Any help would be appreciated! 任何帮助,将不胜感激!

Last line controller/method passed in AJAX should be echo of something. 在AJAX中传递的最后一个行controller/method应该是某些东西的回声。 At the end you would have something like: 最后,您将获得以下内容:

if ($expression) {
    echo json_encode($something);
} else {
    echo json_encode($something_else);
}

Tpojka answer will work. Tpojka的答案会起作用。

But there is a more elegant way to return a JSON objet with CI 但是,有一种更优雅的方法可以返回带有CI的JSON对象

$this->output
        ->set_content_type('application/json')
        ->set_output(json_encode(array('foo' => 'bar')));

http://www.codeigniter.com/userguide3/libraries/output.html#CI_Output::set_content_type http://www.codeigniter.com/userguide3/libraries/output.html#CI_Output::set_content_type

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM