如何使用javascript显示服务器响应? [英] How to show server responses using javascript?

查看:136
本文介绍了如何使用javascript显示服务器响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用ajax提交表单并显示相关消息(提交/出了点问题).我有一个带有要提交到服务器的表单的页面,我正在使用javascript/ajax将请求发送到服务器.如何从服务器接收响应并将其显示在页面上?

I need to submit a form and show related message (submitted / something went wrong) using ajax. I have a page with a form to submit to server, I am using javascript/ajax to send requests to server. how to receive the responses from server and show them on the page ?

当前,我已经写了"xmlhttp.responseText",但是如果我需要显示服务器的响应呢?

Currently I have written "xmlhttp.responseText" , but how about if I need to show the responses of server ?

我也使用以下内容来显示消息,但仅当我使用表单而不是JavaScript发送请求时,该消息才起作用.

I used the following as well to show the message but it only works when I send the request using my form not the javascript.

还有其他显示变量值的方法吗?服务器响应ajax请求后?

Any other way to show value of variables? after server responded to ajax request?

财产

      <s:property value="message"/> 

javascript函数

javascript function

function AddToWatchList(value){
    if(window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            document.getElementById("message").innerHTML = xmlhttp.responseText;
        } 
    }
    xmlhttp.open("get","add?myvalue="+value,false);
    xmlhttp.send();
}

服务器代码

 ...
 private String message;
  public String add(){
    ....
    this.message = "added";
    return "success";
}
 getter and setter of message
 .....

xmlhttp.responseText不是正确的答案,因为我想显示特定变量的值,可以说服务器上的消息变量.

xmlhttp.responseText is not the correct answer as I want to show the value of a specific variable, lets say message variable on the server.

Mor Moordio先生,提供了很好的解决方案,但是有更好的方法吗?

推荐答案

您需要将服务器响应发送到单独的页面,并使用jquery.html或xmlhttp.responseText显示该页面.

You need to send the server response to a separate page and display that page using jquery.html or xmlhttp.responseText.

private String message;
  public String add(){
    ....
    this.message = "added";
    return "message";   
}

struts.xml

struts.xml

<result name="message">message.jsp</result>

message.jsp

message.jsp

   required library goes here
   <s:property value="message"/> 

其余的代码应该没问题.

The rest of your code should be fine.

这篇关于如何使用javascript显示服务器响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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