2016-07-27 69 views
0

我有一个HTML格式如下。我试图使它成为这个POST的响应(字符串)成为id =“answer”的文本。如何让HTML表单的响应更新页面上的文本?

<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"> </script> 
    <script src="http://malsup.github.com/jquery.form.js"></script> 
    <script src="form.js"></script> 
</head> 
<body> 
    <form id="myForm" 
      action="http://myserver.com/post-destination/" 
      method="post"> 
     <p><label>Input: <br><textarea name="formInput"></textarea></label></p> 
     <p><input type="submit" value="Submit" /></p> 
    </form> 
    <p id="answer">?</p> 
</body> 

我试图使用jQuery的表格插件在一个名为form.js文件,其中包括:

$(document).ready(function() { 
    $('#myForm') 
     .ajaxForm({ 
      target: "#answer" 
    }); 
}); 

我在做什么错在这里?我确定这只是一个非常愚蠢的事情,我知道有很多关于HTML表单和jQuery的问题,但是跟着它们被证明是不成功的。我无法弄清楚这一点,因为这是我第一次尝试与网络有关的任何事情。谢谢您的帮助!

回答

0

您的jQuery的Ajax调用似乎是不正确的。您可以重构它如下:

$(document).ready(function() { 
    $('#myForm').submit(function(e) 
{ 
    var postData = $(this).serializeArray(); 
    var formURL = $(this).attr("action"); 
    $.ajax(
    { 
     url : formURL, 
     type: "POST", 
     data : postData, 
     success:function(data, textStatus, jqXHR) 
     { 
      // set the target data 
      console.log ('set the target data'); 
     }, 
     error: function(jqXHR, textStatus, errorThrown) 
     { 
      //if fails 
      console.log ('server responded something else ...'); 
     } 
    }); 
}); 
}); 
+0

Thanks!这似乎工作。我需要重写默认行为,所以它没有加载新页面,但在此之后它工作。 – screamingnugget

0

你可以试试这个:

<head> 
    <script> 
     function text() { 
      var answer = document.getElementById("input").value; 
      document.getElementById("answer").innerHTML = answer; 
     } 
    </script> 
</head> 
<body> 
    <form id="myForm" action="http://myserver.com/post-destination/" method="post"> 
     <p><label>Input: <br><textarea id="input" name="formInput"></textarea></label></p> 
     <p><input onClick="text()" type="submit" value="Submit" /></p> 
    </form> 
    <p id="answer">?</p> 
</body> 
相关问题