jQuery的阿贾克斯 - 问题返回JSON值 [英] jQuery Ajax - issue returning JSON value

查看:129
本文介绍了jQuery的阿贾克斯 - 问题返回JSON值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有得到响应,从服务器的JSON类型的数据。

I'm not getting response as JSON type data from server.

我使用JSON插件。

jQuery( "#dialog-form" ).dialog({ 
    autoOpen: false,
    height: 500,
    width: 750,
    modal: true,
    buttons :{
        "Search" : function(){
            jQuery.ajax({type : 'POST',
            dataType : 'json',
             url : '<s:url action="part" method="finder" />',
         success : handledata})
        }
    }
});
var handledata = function(data)
{
    alert(data);
}

如果的dataType =json的我没有得到任何回应,但如果我不提任何的dataType ,我收到了页面的HTML格式。

If dataType = 'json' I am not getting any response, but if I don't mention any dataType, I'm getting the HTML format of the page.

public String list(){
    JSONObject jo = new JSONObject();
    try {
        Iterator it = findList.iterator();
        while(it.hasNext()){
             SearchResult part = (SearchResult) it.next();
             jo.put("col1",part.getcol1());
             jo.put("col2",part.getcol2());
        }
        log.debug("--------->:"+jo.toString());
    } catch (Exception e) {
        log.error(e);
    }
    return jo.toString();
}

struts.xml中:

<package name="default" namespace="/ajax" extends="json-default">
  <action name="finder" 
       class="action.Part" method="finder" name="finder">
       <result type="json" />
  </action>
</package>

JSP页面:

<div id="dialog-form" >
    <form action="" id="channelfinder">
        <textarea id="products" name="prodnbr"<s:property value='prodNbr'/>   
    </form>
</div>

控制台错误:

org.apache.struts2.dispatcher.Dispatcher - 找不到行动或结果        没有结果的行动定义action.Part        而结果{col1中:COL1,COL2:COL2}

org.apache.struts2.dispatcher.Dispatcher - Could not find action or result No result defined for action action.Part and result {"col1":"col1","col2":"col2"}

的web.xml

web.xml:

    <?xml version="1.0" encoding="ISO-8859-1"?>
     <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
      <display-name>/parts</display-name>
      <description>Parts List Web App</description>

    <filter>
          <filter-name>struts-cleanup</filter-name>
          <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
        </filter>

        <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
        </filter>

       <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
            <param-name>actionPackages</param-name>
            <param-value>com.action</param-value>
        </init-param>
    </filter>


    <filter-mapping>
        <filter-name>struts-cleanup</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
    </filter-mapping>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <error-page>
        <exception-type>java.lang.Throwable</exception-type>
        <location>/errorPage.jsp</location>
    </error-page>
    <error-page>
        <error-code>404</error-code>
        <location>/errorPage.jsp</location>
    </error-page>

  <!-- Spring -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  </web-app>

我没有得到数据的jQuery的成功。 请纠正我,什么是错在这里?

I'm not getting data to jQuery success. Please correct me, whats wrong here?

推荐答案

A 数据类型:JSON所使用的 jQuery的阿贾克斯来指定预计的成功的回调函数时,返回的数据类型的动作和结果被执行,以及来自服务器的响应中返回。

A dataType : 'json' is used by jQuery Ajax to specify a data type that is expected to return by the success callback function when the action and result is executed, and a response returned from the server.

的dataType (默认:智能猜测( XML JSON 剧本 HTML ))

dataType (default: Intelligent Guess (xml, json, script, or html))

类型:字符串

这是你期望从服务器返回的数据的类型。如果没有指定,jQuery将尝试基于MIME类型的反应来推断它(一个XML的MIME类型会产生XML,在1.4 JSON将产生一个JavaScript对象,在1.4脚本将执行该脚本,和其他任何会返回一个字符串)。

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

URL应正确地指向动作映射。假设它会在默认的命名空间,否则你应该修改URL和映射添加命名空间属性。

The URL should correctly point to the action mapping. Assume it will be in the default namespace, otherwise you should modify URL and mapping to add the namespaceattribute.

<script type="text/javascript">
  $(function() {
    $("#dialog-form").dialog ({
      autoOpen: true,
      height: 500,
      width: 750,
      modal: true,
      buttons : {
        "Search" : function() {
          $.ajax({
            url : '<s:url action="part" />',
            success : function(data) {
              //var obj = $.parseJSON(data);
              var obj = data;
              alert(JSON.stringify(obj));
            }
          });
        }
      }
    });
  });
</script>

返回,如果你的的JSONObject 手动生成 JSON 的结果类型是不需要的。您可以返回文本流结果那么,如果需要将字符串转换为JSON。

Returning json result type is not needed if you build the JSONObject manually. You can return text as stream result then convert a string to JSON if needed.

的struts.xml

struts.xml:

<package name="default" extends="struts-default">
  <action name="part" class="action.PartAction" method="finder">    
    <result type="stream">
      <param name="contentType">text/html</param>
      <param name="inputName">stream</param>
    </result>
  </action>
</package>

操作:

public class PartAction extends ActionSupport {

  public class SearchResult {
    private String col1;
    private String col2;

    public String getCol1() {
      return col1;
    }

    public void setCol1(String col1) {
      this.col1 = col1;
    }

    public String getCol2() {
      return col2;
    }

    public void setCol2(String col2) {
      this.col2 = col2;
    }

    public SearchResult(String col1, String col2) {
      this.col1 = col1;
      this.col2 = col2;
    }
  }

  private InputStream stream;

  //getter here
  public InputStream getStream() {
    return stream;
  }

  private List<SearchResult> findList = new ArrayList<>();

  public List<SearchResult> getFindList() {
    return findList;
  }

  public void setFindList(List<SearchResult> findList) {
    this.findList = findList;
  }

  private String list() {
    JSONObject jo = new JSONObject();
    try {
      for (SearchResult part : findList) {
        jo.put("col1", part.getCol1());
        jo.put("col2", part.getCol2());
      }
      System.out.println("--------->:"+jo.toString());
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println(e.getMessage());
    }
    return jo.toString();
  }

  @Action(value="part", results = {
    @Result(name="stream", type="stream", params = {"contentType", "text/html", "inputName", "stream"}),
    @Result(name="stream2", type="stream", params = {"contentType", "application/json", "inputName", "stream"}),
    @Result(name="json", type="json", params={"root", "findList"})
  })
  public String finder() {
    findList.add(new SearchResult("val1", "val2"));
    stream = new ByteArrayInputStream(list().getBytes());
    return "stream2";
  }
}

我已经把不同结果的结果类型和内容类型,以更好地描述这个想法。你可以返回任何的这些结果,并返回JSON对象或者字符串化与否。字符串化的版本需要解析返回的数据,以获得JSON对象。您也可以选择结果类型更好的序列化,以满足您的需求,但我的目标是要表明,如果您需要序列化的简单对象,然后JSON插件是没有必要得到它的工作。

I have placed different results with result type and content type to better describe the idea. You could return any of these results and return JSON object either stringified or not. The stringified version requires to parse returned data to get the JSON object. You can also choose which result type better serializes to suit your needs but my goal was to show that if you need to serialize the simple object then json plugin is not necessary to get it working.

参考文献:

这篇关于jQuery的阿贾克斯 - 问题返回JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆