简体   繁体   English

如何正确处理一个ajax请求

[英]How to handle properly an ajax request

I was curious about how to get autocomplete working in my test application I am developing with Laravel 4, just for practise. 我很好奇如何在我使用Laravel 4开发的测试应用程序中实现自动完成功能。 So I just googled it and found this library , with jQuery as its only dependency. 所以我只是用谷歌搜索并找到了这个库 ,其中jQuery是其唯一的依赖项。

I am not an expert of JavaScript and jQuery and I don't know anything about AJAX, I just did what the manual said and with a bit of common sense figured how it worked overall. 我不是JavaScript和jQuery的专家,对AJAX一无所知,我只是按照手册中的内容做,并根据一些常识确定了它的整体工作原理。

Here's the JavaScript code that applies the autocomplete operation: 这是应用自动完成操作的JavaScript代码:

$('#autocomplete').autocomplete({
    serviceUrl: '/search',
    onSelect: function(suggestion) {
        $('#autocomplete-suggestions').html("<a href='users/" + suggestion.data + "'>" + suggestion.value + "</a>");
    }
})

I defined the services in the routes.php file, since it's very short: 我在routes.php文件中定义了服务,因为它很短:

Route::get('search', function() {
    $users = User::all();
    $response = array(
        "suggestions" => array()
    );
    foreach ($users as $user) {
        array_push($response["suggestions"], array("value" => $user->username, "data" => $user->id));
    }

    return Response::json($response);
});

The way this works got me wondering. 这种工作方式让我感到奇怪。 I mean, every time the user types a character in the input box a request is made and the service is executed, which is in the routes method. 我的意思是,每当用户在输入框中键入一个字符时,都会发出一个请求并执行该服务,这是在route方法中。 This implies retrieving all the users from the database, storing them in an array and then copying it all again to a new array so it adjusts to the expected input. 这意味着从数据库中检索所有用户,将它们存储在一个数组中,然后将所有用户再次复制到一个新的数组中,以适应所需的输入。 And then, on that json the actual search is made. 然后,在该json上进行实际搜索。

This seem very inefficient to me, since this operation has a cost and it is performed with great frequency. 这对我来说似乎效率很低,因为此操作需要一定的成本,而且执行频率很高。 It would be way better if the search was made as a query against the database, instead of an object product to a couple of copies of (potentially) a lot of data. 如果将搜索作为对数据库的查询而不是对大量(可能)大量数据进行复制的对象乘积进行搜索,那会更好。

Also, I seeded some new users with this piece of code: 另外,我用这段代码为一些新用户播种:

for ($i = 0; $i<1000; $i++) {
    $user = new User;
    $user->username = 'username' . $i;
    // assign the rest of the attributes
    $user->save();
}

And it seemed like the search wasn't made properly. 而且搜索似乎没有正确进行。 I guess this is a different issue, concerning the autocomplete library itself. 我猜这是一个与自动完成库本身有关的不同问题。

So, since I am not familiar with AJAX, I just want to know if this is the usual way to operate, or if this is indeed a terrible idea as I think. 因此,由于我不熟悉AJAX,所以我只想知道这是否是常用的操作方式,或者我认为这确实是一个可怕的想法。 What would be the proper way to do it? 正确的做法是什么?

Should I be returning all users with each request and searching on the client side? 我应该在每个请求中返回所有用户并在客户端进行搜索吗?

Absolutely not. 绝对不。 When the request is made to your server via AJAX, the search query is supplied as a query string parameter. 通过AJAX向服务器发出请求时,搜索查询将作为查询字符串参数提供。 From their docs: 从他们的文档:

Web page that provides data for Ajax Autocomplete, in our case autocomplete.ashx will receive GET request with querystring ?query=Li, and it must return JSON data in the following format 提供Ajax自动完成数据的网页,在我们的示例中,autocomplete.ashx将接收带有querystring?query = Li的GET请求,并且必须以以下格式返回JSON数据

You can get that from Laravel: $query = \\Input::get('query'); 您可以从Laravel获得: $query = \\Input::get('query');

You should be using that string to search on your users table using eloquent or whatever and returning only matching suggestions. 您应该使用该字符串以雄辩的方式在users表上进行搜索,并且仅返回匹配的建议。

Is it terrible to make a HTTP request with every keystroke? 每次击键都会发出HTTP请求吗?

That library has an option called deferRequestBy . 该库具有名为deferRequestBy的选项。 When given an integer value (milliseconds), it will wait this long until executing the request on a keyUp event. 当给出整数值(毫秒)时,它将等待很长时间,直到对keyUp事件执行请求。 If another keyUp event comes in, it will cancel the first. 如果出现另一个keyUp事件,它将取消第一个事件。 This helps to reduce the number of concurrent requests you may be running. 这有助于减少您可能正在运行的并发请求的数量。

https://github.com/devbridge/jQuery-Autocomplete/blob/master/src/jquery.autocomplete.js#L384-L384 https://github.com/devbridge/jQuery-Autocomplete/blob/master/src/jquery.autocomplete.js#L384-L384

Directly from their Readme on Github : 直接来自他们在Github上自述文件

deferRequestBy : Number of miliseconds to defer ajax request. deferRequestBy :推迟ajax请求的毫秒数。 Default: 0. 默认值:0

So to answer your question: 因此,回答您的问题:

So, since I am not familiar with AJAX, I just want to know if this is the usual way to operate, or if this is indeed a terrible idea as I think. 因此,由于我不熟悉AJAX,所以我只想知道这是否是常用的操作方式,或者我认为这确实是一个可怕的想法。 What would be the proper way to do it? 正确的做法是什么?

Yes, if you use the default of 0, it probably is a terrible idea. 是的,如果使用默认值0,这可能是一个糟糕的主意。 But it doesn't have to be. 但这不是必须的。

Other points from your question: 您问题的其他要点:

  1. Do you really need to go to the DB and get all the users each time. 您是否真的需要去数据库并每次都获得所有用户。 How about caching? 缓存如何?

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

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