如何使用ajax将json数据发送到服务器

5

refer.jvmhost.net/refer247/registration,这是我的url,我需要获取像用户详情这样的请求,并以json格式获得适当的响应,如果包含状态n错误,则应该有相应的错误信息。请勿提供安卓代码。

这是一个html页面。

<head>
        <script type="text/javascript" src="json2.js"></script>
</head>
<body>
    <div data-role="page" data-theme="c">
        <div data-role="header" data-position="fixed" data-inset="true" class="paddingRitLft" data-theme="c">
            <div data-role="content" data-inset="true"> <a href="index.html" data-direction="reverse"><img src="images/logo_hdpi.png"/></a>

            </div>
        </div>
        <div data-role="content" data-theme="c">
            <form name="form" method="post" onsubmit="return validate()">
                <div class="logInner">
                    <div class="logM">Already have an account?</div>
                    <div class="grouped insert refb">
                        <div class="ref first">
                            <div class="input inputWrapper">
                                <input type="text" data-corners="false" class="inputrefer" placeholder="Userid" name="userid" id="userid" />
                            </div>
                            <div class="input inputWrapper">
                                <input type="password" data-corners="false" class="inputrefer" placeholder="Password" name="password" id="password" />
                            </div>  <a href="dash.html" rel="external" style="text-decoration: none;"><input type="submit" data-inline="true" value="Submit" onclick="json2()"></a>

                            <p><a href="#" style="text-decoration: none;">Forgot Password</a>

                            </p>
                        </div>
                    </div>
                    <div class="logM">New user? Create refer Account</div>
                    <input type="button" class="btnsgreen" value="Sign Up! its FREE" class="inputrefer" data-corners="false" data-theme="c" />
            </form>
            </div>
        </div>
        <p style="text-align: center;">&#169; refer247 2013</p>
    </div>
</body>

这是json2.js文件

function json2()
    {
    var json1={"username":document.getElementById('userid').value,
               "password":document.getElementById('password').value, 
              };
    //var parsed = jsonString.evalJSON( true );
    alert(json1["username"]);
    alert(json1["password"]);
};

请告诉我如何将JSON数据发送到该URL并获取一些响应,例如如果使用该ID注册,则已存在电子邮件ID。 然后给出一些错误,例如电子邮件ID已经存在,并且如果成功注册,则给出类似于已成功注册和状态消息的响应..200 okk ...


https://dev59.com/-G855IYBdhLWcg3wbzxl - Anup
1
$.ajax({ url: "refer.jvmhost.net/refer247/registration", type: 'POST', contentType:'application/json', data: JSON.stringify(json1), dataType:'json' }); success: function(json1){ console.log("Success: "+json1.userid); }, error:function(json1){ console.log("Error: "+json1); }; };这是ajax代码...可能包含一些错误...但我不知道...所以请找出并纠正它 - Seenu69
4个回答

5

您可以使用ajax将JSON数据发布到指定的URL/控制器方法。在下面的示例中,我正在发布一个JSON对象。您还可以逐个传递每个参数。

var objectData =
         {
             Username: document.getElementById('userid').value,
             Password: document.getElementById('password').value                
         };

var objectDataString = JSON.stringify(objectData);

$.ajax({
            type: "POST",
            url: "your url with method that accpects the data",
            dataType: "json",
            data: {
                o: objectDataString
            },
            success: function (data) {
               alert('Success');

            },
            error: function () {
             alert('Error');
            }
        });

而且你的方法只能有一个字符串类型的参数。

     [HttpPost]
    public JsonResult YourMethod(string o)
    {
      var saveObject = Newtonsoft.Json.JsonConvert.DeserializeObject<DestinationClass>(o);
     }

1
除非服务器响应的是 JSON,否则不需要将 dataType 设置为 json。 - kasper Taeymans

1
$.ajax({
    url: urlToProcess,
    type: httpMethod,
    dataType: 'json',
    data:json1,
    success: function (data, status) {
        var fn = window[successCallback];
        fn(data, callbackArgs);
    },
    error: function (xhr, desc, err) {
       alert("error");
    },
});

1
function addProductById(pId,pMqty){
            $.getJSON("addtocart?pid=" + pId + "&minqty="+ pMqty +"&rand=" + Math.floor((Math.random()*100)+1), function(json) {
                alert(json.msg);
            });
        }

这是一个简单的例子,将在按钮点击或onclick事件时调用addtocart servlet,并传递两个参数,即pId和pMqty。成功完成后,它将返回在servlet中设置为json的警报消息。请保留HTML标签。

-1
var json1={"username":document.getElementById('userid').value,
               "password":document.getElementById('password').value, 
};

$.ajax({
    url: '/path/to/file.php',
    type: 'POST',
    dataType: 'text',//no need for setting this to JSON if you don't receive a json response.
    data: {param1: json1},
})
.done(function(response) {
    console.log("success");
    alert(response);
})
.fail(function() {
    console.log("error");
})
.always(function() {
    console.log("complete");
});

在服务器上,您可以接收JSON并像这样解码它:

$myjson=json_decode($_POST['param1']);

阅读问题:“应该以JSON格式获取适当的响应”。另外从评论中可以看到:“contentType:'application / json'”,因此服务器也期望JSON。你认为为什么OP在服务器上使用PHP? - a better oliver

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接