代码之家  ›  专栏  ›  技术社区  ›  Juri Glass

jQuery-如何通过Ajax放置JSON?

  •  60
  • Juri Glass  · 技术社区  · 16 年前

    jQuery

    $.ajax({
        type: "PUT",
        url: myURL,
        contentType: "application/json",
        data: {"data": "mydata"}
    });
    

    但是在服务器端,我收到一个 data=mydata 字符串,而不是预期的JSON。 Firebug

    3 回复  |  直到 14 年前
        1
  •  54
  •   Andy    9 年前

    我认为数据应该是字符串。对象被转换为查询字符串,这就是您在这里看到的。

    JSON.stringify(obj) 方法将对象转换为字符串。JSON对象的代码可从以下位置获得: https://github.com/douglascrockford/JSON-js/blob/master/json2.js .

    或者,只需将用于创建对象的代码作为文本字符串传递,但我认为这只是一个示例,您需要对已经创建的某个对象进行编码。

        2
  •  31
  •   Peter Mortensen Pieter Jan Bonestroo    14 年前

    如果您总是必须在应用程序中发送JSON,那么您可以在init的某个地方执行它,然后使用默认值 $.ajax 在您的示例中调用,它将始终序列化为JSON字符串,而不是Ajax默认查询字符串。

    $.ajaxSetup({
        contentType : 'application/json',
        processData : false
    });
    $.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
        if (options.data){
            options.data=JSON.stringify(options.data);
        }
    });
    
        3
  •  1
  •   Peter Mortensen Pieter Jan Bonestroo    14 年前
    //url: this is a reference to the XML, where you need to define the mapping.
    //<entry key="/getEmpDetails/transEfileGenerate.app">
    //<bean class="com.adp.ems.framework.spring.MappingItem" p:delegate-ref="efilePageDelegate"
    //p:action="passJSONObjectAndGetWebServiceOutput" />
    
    //str1 is the input JSON that you need to pass... Ajax will automatically take care to get the response.
    //</entry>
    
    var kw = {
        url : "getEmpDetails/transEfileGenerate.app",
        timeout : 30000,
        handleAs : "json",
        sync: false,
        putData : str1,
        headers: { "Content-Type": "application/json"},
        load : function(result) {
    },