简体   繁体   English

使用AJAX和CodIgniter发送信息

[英]Sending information with AJAX and CodIgniter

Hey guys I am building an application in which I send input value from a text box via AJAX to a controller function and then return what I send back to the user (I am developing an instant search, this is a first step). 大家好,我正在构建一个应用程序,在该应用程序中,我通过AJAX将来自文本框的输入值发送到控制器功能,然后将发送回的值返回给用户(我正在开发即时搜索,这是第一步)。

The AJAX links to the method fine however I am having problems returning the information. AJAX链接到方法很好,但是我在返回信息时遇到问题。 I receive no error messages, the problem is that the return string is BLANK. 我没有收到任何错误消息,问题是返回字符串为BLANK。 I receive [you wrote ] rather than [you wrote WHATEVER I IN PUTTED ] 我收到的是[您写的],而不是[您写的是我写的内容]

Any help greatly appreciated. 任何帮助,不胜感激。

view_index.php view_index.php

function search(){

var term = document.getElementById("mainsearch").value;

$.ajax({
        type: "POST",
        url: "<?php echo base_url('index.php/site/search/')?>",
        data: term,
        cache: false,
        success: function(html){
            alert("you wrote " + html);
        }
    });

controller_site.php controller_site.php

function search(){
    $gotcha = $this->input->post('term');
    return $gotcha;
}

The data: parameter accept a key : value json to pass to the POST, as the json array key will be your $_POST key data:参数接受一个key : value json传递给POST,因为json数组密钥将是您的$_POST密钥

Try with this: 试试这个:

$.ajax({
    type: "POST",
    url: "<?php echo base_url('index.php/site/search/')?>",
    data: {'term': term }
    cache: false,
    success: function(html){
        alert("you wrote " + html);
    }
});

You didn't send your data correctly, so PHP has nothing to process, and you end up sending back nothing: 您没有正确发送数据,因此PHP无需处理,最终没有返回任何内容:

    data: term,

POST/GET requests MUST be in key=value format, and you're sending only the value portion. POST / GET请求必须采用key=value格式,并且您只发送value部分。 Try 尝试

 data: {foo: term},

and then 接着

 $gotcha = $this->input->post('foo');

You need to change return to echo as AJAX response works on whatever echo from called function. 您需要更改echo return ,因为AJAX响应可处理来自调用函数的任何echo

So, you can code like : 因此,您可以像这样进行编码:

function search(){ $gotcha = $this->input->post('term'); echo $gotcha; }

or 要么

function search(){ echo = $this->input->post('term'); }

The responseText property returns the response as a string, and you can use it accordingly responseText属性以字符串形式返回响应,您可以相应地使用它

It is generally a bad idea to return HTML from your controllers. 从控制器返回HTML通常是一个坏主意。 Instead try to just manage data server-side wise and do all the frontend on the client side. 相反,请尝试仅在服务器端明智地管理数据,并在客户端进行所有前端。

Now, for the error: 现在,对于错误:

  1. The success callback takes 3 parameters 成功回调具有3个参数
  2. You need to pass key-value pair in the data argument of the .ajax call 您需要在.ajax调用的data参数中传递键值对
  3. Make sure you handle errors on your controller appropriately because if something goes wrong you'll get an html document as a response from CodeIgniter and you'll spend a lot of time debugging javascript to find out that the error was actually server-side 确保适当地处理控制器上的错误,因为如果出现问题,您会从CodeIgniter获得html文档作为响应,并且将花费大量时间调试javascript以发现错误实际上是服务器端的

1 the callback: 1.回调:

Your success callback function should look like this: 您的成功回调函数应如下所示:

function (data, status, response) {

}

Where: 哪里:

  • data is whatever you are echoing from your controller's method. 数据就是您要从控制器方法中回显的一切。 You'll probably want JSON. 您可能需要JSON。
  • status Will tell you if the HTTP response message (eg "Not Found" is the status for a 404 code, "success" for a 200 code) status会告诉您HTTP响应消息(例如,“ Not Found”是404代码的状态,“ success”是200代码的状态)
  • response is the jquery wrapped XmlHttpRequest object that gives you a handful information of the transaction, for example response.responseText would give you whatever you outputed from PHP, response.responseJSON would give you a JSON object if you echoed a json encoded object, etc. response是用jquery包装的XmlHttpRequest对象,它为您提供了一些事务信息,例如response.responseText将为您提供从PHP输出的任何内容,如果您回显json编码的对象,则response.responseJSON将为您提供JSON对象等

Why should you care? 你为什么要在乎呢? Because those extra parameters will let you decide if something went wrong on your backend so you can handle the situation client-side not leaving the user wondering if you app just don't work. 因为这些额外的参数可以让您确定后端是否出了问题,所以您可以处理客户端的情况,而不会让用户怀疑您的应用程序是否不起作用。 Worse, giving the infamous red cross on the status bar of the browser. 更糟糕的是,在浏览器的状态栏上出现了臭名昭著的红叉。

If you set the dataType parameter of the jQuery.ajax function then you can explicitly tell jQuery what kind of data you are expecting to be retrieved from the server on data parameter from your callback. 如果您设置dataType的参数jQuery.ajax功能,那么你可以明确地告诉jQuery的什么样的数据,你期望从服务器上获取data从您的回调参数。

2 the sent data 2发送的数据

As said, you need to either pass value-pairs or a URL encoded string. 如前所述,您需要传递值对或URL编码的字符串。 If you intend to use GET then you can pass the URL encoded string, but that means you have to have arguments on your CI function like: 如果打算使用GET,则可以传递URL编码的字符串,但这意味着您必须在CI函数上具有如下参数:

function search($term)

And then CI automatically routes the incoming parameters. 然后,CI自动路由传入的参数。 But since you want to do POST then you'll want to effectively get the values with $this->input->post("name") 但是,由于您要执行POST,因此您将需要使用$this->input->post("name")有效地获取值

If you have your input inside a form, or several fields that you need to send, then its easier to just serialize the form: 如果您在表单或需要发送的多个字段中输入内容,则只需序列化表单即可:

$.ajax("url", {
    type : 'POST',
    data : $('#form').serialize(),
    dataType : 'json',
    success : function(data, status, response) {}   error : function(response, status error) {}});

3 handle errors 3处理错误

If you are relying on AJAX then make sure that you return some sort of error or warning so you can catch it client side: 如果您依赖AJAX,请确保您返回某种错误或警告,以便可以在客户端捕获它:

function search() {
    $term = $this->input->post("term")
    if($term == FALSE) {
        //return a 404 so that you can catch .error on jquery 
    } else  {
        echo $term;
    }
}

Do a research on RESTFul apps. 对RESTFul应用进行研究。 It'll help you a lot understanding that. 它会帮助您很多理解。 this is a good starting point and although your question was not exactly related to this, it is a good practice to have separate layers on your application so that you just consume data from your backend, handle situations and then just react accordingly on the frontend, that is, you just use javascript to either send, receive and list data. 这是一个很好的起点 ,尽管您的问题并不完全与此相关,但是将应用程序放在不同的层上是一个好的习惯,这样您就可以从后端使用数据,处理情况,然后在前端做出相应的反应,也就是说,您只需要使用JavaScript即可发送,接收和列出数据。 If you are using CI or any other MVC framework then you should not really be generating HTML on your controllers, thats what the views are for. 如果您正在使用CI或任何其他MVC框架,那么您实际上不应该在控制器上生成HTML,这就是视图的作用。

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

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