繁体   English   中英

在jQuery中的getJson之后发布json数据

[英]post json data after getJson in jquery

我有一个关于如何同时使用GET和POST的问题。 我想要做的是在保存表单之前,我想验证新用户名是否不存在。

{ “status”: “success”, “results” : [ { “id” : 1, “name” : “John Smith”, “password”: “123456” }, { “id”: 2, “name” : “Jane Doe”, “password”: “654321” } ] }

我想在保存表单之前编写代码来验证用户名不存在。 如果用户名存在,我想向浏览器显示警报。 如果没有错误,我想提交表格。

到目前为止,这就是我得到的! 任何帮助将不胜感激!

$('form').submit(function(event) {
var username = $('#user_name').val();

$.getJSON('user.json', function(data) {

    var results = data.results;
    var match = false;

    $.each(results, function(i, result) {
        if(result.name === username) {
            match = true;
        }
    });

    if(!match) {
        console.log("POST");
        // Submit the form!


    } else {
        alert("Username already exists!");
    }

});

});

有更好的方法吗? 即使不使用jQuery? 使用jQuery的充分理由是什么?

检查以下代码以json格式发送一些数据。

if(!match) {
        console.log("POST");

    $.ajax({
        cache: false,
        url : ?,
        type: "POST",
        dataType : "json",
        data : JSON.stringify(data),
        context : Form,
        success : function(callback){
            //Where $(this) => context == FORM
            console.log(JSON.parse(callback));
            $(this).html("Success!");
        },
        error : function(){
            $(this).html("Error!");
        }
    });
}

删除数据:JSON.stringify(data),以防您不需要。

暂无
暂无

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

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