【问题标题】:jQuery ajax POST returning results in blank pagejQuery ajax POST 在空白页面中返回结果
【发布时间】:2013-12-04 00:14:03
【问题描述】:

预期行为

01 - 使用 jQuery 发布表单。
02 - 授权已处理。
03 - 执行 MongoDB 查询。
04 - 结果应代替表格返回。

实际行为

步骤 1 - 3 已完成,但步骤 4 未完成;正在返回正确的结果,但在空白页中。

表格

<form name="login" id="login">
<p>username</p>
<p>password</p>
<input type="text" name="username" />
<input type="password" name="password" />
<button type="submit">login</button>
</form>

jQuery

<script>
$(document).ready(function() {
$('#login').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/login',
data: $(this).serialize(),
dataType: 'json',
success: function(results) {
$("#content_area").html("");
$("#content_area").append(results.content);
}
});
});
});
</script>

Python

@post('/login')
def login():
    """Authenticate users"""
    username = post_get('username')
    password = post_get('password')
    aaa.login(username, password, fail_redirect='/login')
    dbname = 'mydb'
    connection = pymongo.MongoClient(os.environ['OPENSHIFT_MONGODB_DB_URL'])
    db = connection[dbname]
    collection = db.myCollection
    href = 'my-title'
    query = {'title':href}
    projection = {'_id':0,'content':1}
    cursor = collection.find_one(query,projection)
    response.content_type = 'application/json'
    return dumps(cursor)

【问题讨论】:

    标签: jquery ajax mongodb python-2.7 bottle


    【解决方案1】:

    当您在 ajax 请求期间有 document.write() 调用时会出现此问题。

    【讨论】:

      【解决方案2】:

      解决方案:

      登录表单页面的内容(即&lt;form&gt; 而不是html &lt;head&gt;)由getJSON() 加载。

      长话短说,我想:

      如果 jQuery 没有正确加载,因为内容是 通过 getJSON() 加载?

      所以我将 jQuery 脚本更改为使用 .on 即:

      <script>
      $(document).on("submit","#login", function (e) {
      e.preventDefault();
      $.ajax({
      type: 'POST',
      url: '/login',
      data: $(this).serialize(),
      dataType: 'json',
      success: function(results) {
      $("#content_area").html("");
      $("#content_area").append(results.content);
      }
      });
      });
      </script>
      

      现在它可以在指定的 div 中正确加载。

      【讨论】:

        【解决方案3】:

        替换这个:

        response.content_type = 'application/json'
        

        用这个:

        response.set_header('Content-type', 'application/json')
        

        (只是猜测。)

        【讨论】:

        • 仅供参考,没有效果。
        • 糟糕,刚刚意识到:应该是content-type,而不是content_type。我会更正我的答案 - 运气好的话会解决你的问题。
        • 那没有效果。
        • 无赖。祝你好运。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-06
        • 2014-06-01
        • 1970-01-01
        相关资源
        最近更新 更多