0

我知道这是一个经常在许多帖子中出现的问题,但即使在阅读了几十个答案之后,我仍然无法弄清楚我的代码有什么问题。

重点是防止默认提交和检索答案 div 中的响应数据。代码的实际作用是将我直接发送到 geocoder.php 页面。

非常感谢,

    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>

<script>
/* attach a submit handler to the form */
$("geostring").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* get some values from elements on the page: */
  var $form = $( this ),
      term = $form.find( 'input[name="geo"]' ).val(),
      url = $form.attr( 'action' );

  /* Send the data using post */
  var posting = $.post( url, { s: term } );

  /* Put the results in a div */
  posting.done(function( data ) {
    var content = $( data ).find( '#content' );
    $( "#answer" ).empty().append( content );
  });
});
</script>



<form action="http://winefy.alwaysdata.net/geocoder.php" method="POST" id="geostring">
<input type=text name="geo" placeholder="Address..." />
<input type="submit" value="Geocode" />
<div id="answer"></div>
</form>
4

2 回答 2

3

两件事情:

  1. 正如DCoder在下面的评论中指出的那样,您的选择器缺少#. 应该是$("#geostring"),不是$("geostring")

  2. 您试图在form元素存在之前附加处理程序。所以$("#geostring")返回一个空的 jQuery 集,并且没有连接任何处理程序。

    只需将script标签放在.form

    <form action="http://winefy.alwaysdata.net/geocoder.php" method="POST" id="geostring">
    <input type=text name="geo" placeholder="Address..." />
    <input type="submit" value="Geocode" />
    <div id="answer"></div>
    </form>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    
    <script>
    /* attach a submit handler to the form */
    $("#geostring").submit(function(event) {
    
      /* stop form from submitting normally */
      event.preventDefault();
    
      /* get some values from elements on the page: */
      var $form = $( this ),
          term = $form.find( 'input[name="geo"]' ).val(),
          url = $form.attr( 'action' );
    
      /* Send the data using post */
      var posting = $.post( url, { s: term } );
    
      /* Put the results in a div */
      posting.done(function( data ) {
        var content = $( data ).find( '#content' );
        $( "#answer" ).empty().append( content );
      });
    });
    </script>
    

    更多的:

    或者,如果script由于某种原因您无法控制标签的位置,您可以使用 jQuery 的ready事件来延迟您的代码,直到 DOM 加载。

    $(function() {
        // ...your code here...
    });
    

    或更详细地说:

    $(document).ready(function() {
        // ...your code here...
    });
    
于 2013-06-23T07:32:57.937 回答
1

您始终可以使用常用方法:

<form onsubmit="return myFunc();"></form>

<script type="text/javascript">
function myFunc(){
    // Your jQuery Code
    return false;
}
</script>
于 2013-06-23T07:51:01.187 回答