weixin_33709219 2018-05-13 11:20 采纳率: 0%
浏览 4

HTML帖子无法正常运行

I am trying to make a simple website that posts information to an api and shows output as alert. But I can't get any alert. Code:

<!DOCTYPE html>
    <html>
        <body>
            <b>Enter name</b>
            <br>
                <input type="text" id="name">
            <br>
            <button id="button1">Submit</button>
            <script
             src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
            </script>
    <script>$('#button1').click(function(){
        $.ajax({
            type: "POST",
            url: "http://(api url)",
            data :{name:$('#name').value()},
        });
    });   
    </script>
    </body>
    </html>
  • 写回答

2条回答 默认 最新

  • weixin_33727510 2018-05-13 11:30
    关注

    If you want to show the result in alert, in that case you need to handle the success callback like following.

      $.ajax({
          type: 'POST',
          url: "http://(api url)",
          data: {name:$('#name').val()}
          success: function(result) { alert(result) }
        });
    

    success Type: Function( Anything data, String textStatus, jqXHR jqXHR ) A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn

    Note that, value() is nothing in jQuery, you need to use val()

    I suggest, along with success, you should also handle the error like following.

    error: function(XMLHttpRequest, textStatus, errorThrown) {
         alert("Some error occurred");
      }
    

    For more details on $ajax, I suggest you to go through the documentation here

    评论

报告相同问题?