jQuery 如何通过 ajax 将 JSON 数据传递给 Restful Web 服务,以及如何获取 JSON 数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19557184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:12:52  来源:igfitidea点击:

how to pass JSON data to restful web services through ajax and also how to get JSON data?

jqueryajaxjsonrest

提问by Jagathesewaren Kuppuraj

Hi, I am new to JSON .My question is how to pass JSON data to restful web services through ajax?

嗨,我是 JSON 新手。我的问题是如何通过 ajax 将 JSON 数据传递给 Restful Web 服务?

Please Help me.

请帮我。

I tried by following code but I am not sure about it

我尝试了以下代码,但我不确定

MY INDEX PAGE

我的索引页

<script type="text/javascript">

 $(document).ready(function(){  

     var uname = document.getElementById("uname").value();
     var password = document.getElementById("pwd").value();


     $('#ok').click(function(){  
         $.ajax({  
             url:'http://localhost:8090/LoginAuthRWS/rest/orders',  
             type:'post',  
             dataType: 'Jsondemo',


             success: function(data) {  
                 $('#name').val(data.name);  
                 $('#email').val(data.email);  

                 var JSONObject= {
                         "uname":uname,
                         "password":password
                         };
             }  
         });  
     });  
}); 

</script>  

回答by Arvind

var JSONObject= {"uname":uname, "password":password };
var jsonData = JSON.parse( JSONObject );    

var request = $.ajax({
  url: "rest/orders",
  type: "POST",
  data: jsonData,
  dataType: "json"
});        

回答by Satpal

Problems with your code:

您的代码存在的问题:

  • .valueis a property not an function
  • You want to pass json use dataof $.ajax
  • There no data type as Jsondemoyou have to use JSON
  • if response datais not JSON you can use $.parseJSONto convertit to JSON
  • .value是属性而不是函数
  • 你想通过JSON使用data$.ajax
  • 没有Jsondemo您必须使用的数据类型JSON
  • 如果响应data不是 JSON,您可以使用$.parseJSON将其转换为 JSON

Complete Code

完整代码

$(document).ready(function(){  
    $('#ok').click(function(){  
        var uname = document.getElementById("uname").value;
        var password = document.getElementById("pwd").value;
        var JSONObject= {
             "uname":uname,
             "password":password
             };

        $.ajax({  
            url:'http://localhost:8090/LoginAuthRWS/rest/orders',  
            type:'post',
            data :  JSONObject,      
            dataType: 'JSON',
            success: function(data) { 
                     var jsonData = $.parseJSON(data); //if data is not json
                     $('#name').val(jsonData.name);  
                     $('#email').val(jsonData.email);  
                }  
        });  
    });  
});      

回答by Sergey

jQuery dataTypeReference.

jQuerydataType参考

Possible dataTypevalues : xml, json, script, or html

可能的dataType值:xmljsonscript,或者html

Try this:

尝试这个:

var dataToServer = { 
  uname : document.getElementById("uname").value,
  document.getElementById("pwd").value
};

$.ajax({  
  url:'http://localhost:8090/LoginAuthRWS/rest/orders',  
  type:'post',  // or put
  contentType: 'application/json', // type of data
  data: JSON.stringify(dataToServer) // make JSON string
  dataType: 'json', // type of return result
  success: function(data) {  
    $('#name').val(data.name);  
    $('#email').val(data.email);  
  }  
});  

回答by Anto Robinson

To pass the values to web services Ajax have dataattribute.

要将值传递给 Web 服务,Ajax 具有data属性。

<script type="text/javascript">

$(document).ready(function(){  

 var uname = document.getElementById("uname").value;
 var password = document.getElementById("pwd").value;


 $('#ok').click(function(){  
     $.ajax({  
         url:'http://localhost:8090/LoginAuthRWS/rest/orders',  
         type:'post',  
         dataType: 'Json',

         data:{
           uname:uname,
           password:password
         },

         success: function(data) {  
             $('#name').val(data.name);  
             $('#email').val(data.email);
         }  
     });  
  });  
}); 

</script>  

回答by Vidya

You want to do something like this:

你想做这样的事情:

$('#ok').click(function(){  
         $.ajax({  
             url:'http://localhost:8090/LoginAuthRWS/rest/orders',  
             type:'post',  
             dataType: 'json',
             data: { name: "John", location: "Boston" }

             success: function(data) {  
                 response = $.parseJSON(data);
                 $('#name').val(response.name);  
                 $('#email').val(response.email);      
             }  
         });  
});  

A few things to note:

需要注意的几点:

  • dataTypeshould be almost always xmlor json. Sometimes JQuery can guess correctly if you don't provide anything. But it needs to be a real thing.
  • Since you are doing a post, you need to send data to the REST endpoint. That's what I have in data. Note that the kind of data matches the value in dataType. Also note you can use the $.postmethod to do a much simpler post with JQuery.
  • The dataparameter to the success callback needs to be parsed as JSON first (assuming that's what's coming back) since it is of type PlainObjectas described here. That's what $.parseJSONdoes. Once you do that, you can navigate the JSON tree as necessary to do what you need to do. You may be able to get away without doing that though.
  • dataType应该几乎总是xmlor json。有时,如果您不提供任何内容,JQuery 可以正确猜测。但它必须是真实的。
  • 由于您正在发布,您需要将数据发送到 REST 端点。这就是我在data. 请注意,数据类型与 中的值匹配dataType。另请注意,您可以使用该$.post方法使用 JQuery 进行更简单的发布。
  • data给成功回调需要参数首先被解析为JSON(假设这是什么会回来),因为它是类型的PlainObject描述这里。这就是$.parseJSON它的作用。完成此操作后,您可以根据需要导航 JSON 树以执行您需要执行的操作。不过,您可能无需这样做就可以逃脱。

Hope that helps.

希望有帮助。

回答by Devram Kandhare

You can pass json data as request body like this:

您可以像这样将 json 数据作为请求正文传递:

    var JSONObject= {"uname":uname, "password":password };
    $.ajax({
        url : env + 'rest/orders',
        type : 'POST',
        headers: {
            'Content-Type':'application/json'
        },
        data : JSON.stringify(JSONObject),
        dataType   : "json",
    });