为什么这里没有触发ajax请求? [英] Why is an ajax request not being triggered here?

查看:316
本文介绍了为什么这里没有触发ajax请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个自动填充字段,用户可以在其中选择现有标签或创建新标签.如果用户创建了一个新标签,则按下表单按钮,它将POST请求发送到视频控制器中的update操作,该控制器将请求处理为AJAX,并且该标签会显示在字段上方.

So I have an autocomplete field where a user can select an existing or create a new tag. If a user creates a new tag, he presses the form button, and it sends a POST request to the update action in the videos controller which processes the request as AJAX, and the tag gets displayed above the field.

现在,问题是当用户从建议列表中选择标签时.默认情况下,jQuery UI自动完成插件将所选元素添加到字段中,然后用户必须按下表单按钮.但是,我想通过从建议列表中选择标签时自动添加标签来节省用户的精力.因此,我的application.js文件中包含以下代码:

Now, the problem is when a user selects a tag from the suggestion list. By default, the jQuery UI autocomplete plugin appends the selected element inside the field, and then the user has to press the form button. However, I want to save the user some effort by automatically adding the tag right when it's picked from the suggested list. Therefore, I have this code in my application.js file:

select: function(event, ui) {
           var url = $('.edit_video').attr('action');
           var val = ui.item.topic.name;
           $.ajax({type:"PUT", url:url, data:{video:{topic_names:val}}});
           return false;
        }

当从列表中选择一个元素时,它成功向更新操作发送了一个PUT请求.但是,该请求不会作为AJAX处理.该标签已成功添加,但仅在刷新页面后才能添加.我希望将请求作为AJAX处理.我该怎么办?

That successfully sends a PUT request to the update action when an element is selected from the list. However, the request is NOT processed as AJAX. The tag is successfully added, but only after a page refresh. I want the request to be processed as AJAX. How can I do this?

我猜测问题与以下事实有关:当您按下表单按钮时,:remote => true选项告诉rails查找format.js(我在更新操作中具有此功能),但是当没有按下按钮,并且从列表中选择了一个元素,Rails不知道要查找JS.我怎么知道呢?

I'm guessing that the problem has to do with the fact that when you press the form button, the :remote => true option tells rails to look for format.js (which I have in my update action), but when the button is not pressed, and an element is selected from the list, Rails does not know to look for JS. How do I let it know?

推荐答案

在这里我假设不是通过AJAX处理的内容,这意味着它不是在渲染view.js.erb文件,而是在渲染view.html.erb文件反而.您可以通过在JS中强制使用URL格式来解决此问题:

I'm assuming here that by something not being processed as AJAX that you mean that it's not rendering the view.js.erb file, but rather the view.html.erb file instead. You can fix this by forcing the format of the URL in your JS like this:

var url = $('.edit_video').attr('action') + ".js";

然后将其发送为正确的格式以供您执行操作.

That would then send it to the right format for your action.

这篇关于为什么这里没有触发ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆