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

时间:2021-07-12 06:34:42

refer.jvmhost.net/refer247/registration, this is my url,i have to fetch request to this url like user details and should get the appropriate response in json format with status n error if it contains ..dont give me android code..

refer.jvmhost.net/refer247/registration,这是我的网址,我必须获取此网址的请求,如用户详细信息,并应以json格式获取相应的响应状态为n错误,如果它包含..dont给我android代码。 。

this is html page.

这是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>

this is json2.js

这是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"]);
};

so tell me how to send the json data to that url n obtain some response like if email id is already exist if u registering with that id ..then give some error like email id already exist n if registerd succesfully then give respone like registerd successfully and status msg..200 okk...

所以告诉我如何将json数据发送到该url n获取一些响应,如果你注册了那个id就已经存在电子邮件id ..然后给出一些错误,如电子邮件ID已经存在n如果成功注册然后给予respone就像注册成功和状态msg..200 okk ...

4 个解决方案

#1


5  

You can use ajax to post json data to specified url/controller method. In the below sample I am posting an json object. You can also pass each parameter separately.

您可以使用ajax将json数据发布到指定的url / controller方法。在下面的示例中,我发布了一个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');
            }
        });

And your method can have only one parameter of string type.

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

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

#2


1  

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

Here is a simple example, which will call on button click or onclick event and call addtocart servlet and passes 2 argument with it i.e. pId and pMqty.

这是一个简单的例子,它将调用按钮单击或onclick事件并调用addtocart servlet并传递2个参数,即pId和pMqty。

and after successful completion it return message in alert which is set in that servlet in json.

成功完成后,它将在alert中返回消息,该消息在json中的该servlet中设置。

#3


0  

$.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");
    },
});

#4


-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");
});

on the server you can receive you json and decode it like so:

在服务器上,您可以接收json并解码它,如下所示:

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

#1


5  

You can use ajax to post json data to specified url/controller method. In the below sample I am posting an json object. You can also pass each parameter separately.

您可以使用ajax将json数据发布到指定的url / controller方法。在下面的示例中,我发布了一个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');
            }
        });

And your method can have only one parameter of string type.

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

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

#2


1  

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

Here is a simple example, which will call on button click or onclick event and call addtocart servlet and passes 2 argument with it i.e. pId and pMqty.

这是一个简单的例子,它将调用按钮单击或onclick事件并调用addtocart servlet并传递2个参数,即pId和pMqty。

and after successful completion it return message in alert which is set in that servlet in json.

成功完成后,它将在alert中返回消息,该消息在json中的该servlet中设置。

#3


0  

$.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");
    },
});

#4


-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");
});

on the server you can receive you json and decode it like so:

在服务器上,您可以接收json并解码它,如下所示:

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