jQuery ajaxForm返回.json文件 [英] jQuery ajaxForm returning .json file

查看:55
本文介绍了jQuery ajaxForm返回.json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在rails中有一个模型创建表单,我也通过ajax返回JSON. 到目前为止,我的代码如下:

I've got a model creation form in rails which I also have returning JSON through ajax. My code so far look like:

$('#new_stem').ajaxForm({ //#new_stem is my form
  dataType: 'json',
  success: formSuccess
});

function formSuccess(stemObj) {
  //does stuff with stemObj
}

我有一个包含文件上传器的多部分表单(但我不确定是否相关).

And I have a multipart form with a file uploader (but I'm not sure if that is relevant).

当我提交表单时,它工作正常(我的模型已正确创建并呈现为json),但不是由formSuccess函数处理json,而是提示下载"stems.json"(指向我的词干创建动作).

When I submit the form it works fine (my models are properly being created and renders as json), but instead of the json getting handled by the formSuccess function, it prompts a download for "stems.json" (the path to my stem creation action) in Firefox.

什么会导致这种情况发生,什么可以解决?不知道这是否是问题的一部分,但是我的表单中没有提交按钮,我有一个单击处理程序的链接,该处理程序调用$('#new_stem).submit()

What would cause this to happen, and what could solve it? Not sure if this is part of the problem, but I don't have a submit button in my form, I have a link with a click handler that calls $('#new_stem).submit()

谢谢大家!

Firebug告诉我标题包含以下内容:

Firebug tells me the header contains the following:

Etag        "b53e5247e7719cf6b1840e2c6e68781c"
Connection      Keep-Alive
Content-Type    application/json; charset=utf-8
Date        Mon, 03 May 2010 02:19:31 GMT
Server      WEBrick/1.3.1 (Ruby/1.8.7/2010-01-10)
X-Runtime       241570
Content-Length  265
Cache-Control   private, max-age=0, must-revalidate

加上一个cookie标头

plus a cookie header

推荐答案

尽管并非我要解决的问题,但我还是能够找到一个略微不同的解决方案来满足我的需求!

Though not exactly what I was aiming to solve, I was able to come to a slightly different solution that suited my needs!

由于ajax文件是通过iframe上传的,因此问题在于iframe加载了.json文件后,Firefox将其解释为下载并打开了下载提示.我很确定我可以使用一些服务器设置来防止这种情况,但是我已经花了足够的时间进行这项工作.

As ajax file uploads are done through iframes, the issue was that after the iframe loaded the .json file, it was interpreted by Firefox as a download and a download prompt was opened. I am pretty sure I could have played with some server settings to prevent this, but I've already sunk enough time into this.

所以我所做的是将输出呈现为文本而不是json,因为无论如何我实际上只是在寻找一个id号.我的代码现在看起来像:

So what I did was rendered the output as text instead of json because I was only really fishing for one id number anyway. My code now looks like:

$(document).ready(function() {
  $('#continue-upload').click(function() {
    $('#new_stem').ajaxSubmit({
      dataType: 'text', //'json',
      success: formSuccess
    });
  });
});

我需要的ID号也包裹在pre标记中,因此我也需要在结果函数中删除这些ID.

The id number I needed also came wrapped in pre tags, so I needed to strip those off in my results function as well.

这就是我现在想要的,呜!

This does what I want it to now, woo!

这篇关于jQuery ajaxForm返回.json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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