【问题标题】:Unable POST to my API with AJAX & jQuery无法使用 AJAX 和 jQuery POST 到我的 API
【发布时间】:2016-06-24 22:44:39
【问题描述】:

我是 jQuery 和 javascript 的新手,我真的很难 POST 和 GET 到我的 API。当我通过 git bash 命令行执行 curl 请求时,我可以正常发布,但无法通过 JS 和 jQuery 执行此操作。它也无法在我的主 HTML 页面上填充。以下是我的表单代码:

<h2>My Lists:</h2>
<ul id="orders"></ul>

<h3>Add Restaurant</h3>
<form action="" method="POST">
    <p>
        restaurant name: 
        <input type="text" id="name">
    </p>
    <input id="add-rest" type="submit" value="submit">
</form>         
<script src="jquery-1.12.1.min.js"></script>
<script src="script.js" type="application/javascript"></script> 
$(function(){
    var $orders = $('#orders');
    var $name = $('#name');

    $.ajax({
        type: 'GET',
        url: 'http://testing-sh1.appspot.com/restaurant',
        success: function(orders){
            $.each(orders, function(i, order){
                $orders.append('<li>name: ' + order.name + '</li>');
            });
        }
    });
});

$('#add-rest').on('submit', function(){
    var order = {
        name: $name.val(),
    };

    $.ajax({
        type: 'POST',
        url: 'http://testing-sh1.appspot.com/restaurant',
        data: order,
        success: function(newOrder){
            $orders.append('<li>name: ' + newOrder.name + '</li>');
        }
    });
});

我有我的实时 API URL 仅用于测试。希望第二双眼睛可以帮助我。谢谢大家的帮助。

【问题讨论】:

  • 检查您的浏览器控制台以检查是否有任何错误...
  • 您是否在 API 上设置了 CORS?如果不是,您的请求可能会被同源策略停止。检查控制台是否有错误。
  • 如何检查是否设置了 CORS?如果不是,我该如何设置?
  • 您可以检查请求的标头。虽然从你的回答我猜它没有。添加 CORS 标头取决于 API 使用的语言。
  • 我相信我已经设置好了。我在 Google App Engine 上使用 python。 self.response.headers.add_header("Access-Control-Allow-Methods", "GET, POST") self.response.headers.add_header("Access-Control-Allow-Headers", "origin, x-requested-with , 内容类型, 接受") self.response.headers.add_header("Access-Control-Allow-Origin", "*") self.response.headers.add_header('Content-Type', 'application/json')

标签: javascript jquery html ajax api


【解决方案1】:

你有一个错字,在

var order = {
    name: $name.val(),
};

删除尾部, 使其成为有效对象。

我收到了“测试”的回复

{"reviews": [], "name": "test", "key": 5649391675244544}

我直接测试了AJAX。

还要确保变量被正确传递,并且它们是在各自函数的范围内定义的。与您当前的代码一样,var $name = $('#name'); $name 将无法在您的提交处理程序中访问,因为它对于具有不同范围的另一个函数是本地的。

您还需要防止表单提交的默认行为,因为您是通过自定义 AJAX 调用处理事件。

【讨论】:

  • 感谢您的提醒。我想知道您是对订单进行硬编码还是使用了 html 表单。我尝试使用您建议的编辑表单,但我仍然一无所获。
  • 我会为你更新答案,以获得更多关于你可以在哪里寻找问题的提示。
【解决方案2】:
The response you are getting is in string, change it to an object and also when using ajax try to avoid form
And also declare global variables outside function

<h2>My Lists:</h2>
<ul id="orders"></ul>
<h3>Add Restaurant</h3>
<div>
    <p>
        restaurant name: 
        <input type="text" id="name">
    </p>
    <input id="add-rest" type="submit" value="submit">
</div>         
<script type="text/javascript" src="../myspace/js/jquery-1.9.1.min.js"></script>

    <script> 

        var $orders = $('#orders');
        var $name = $('#name');
        $(function(){
            $.ajax({
                type: 'GET',
                url: 'http://testing-sh1.appspot.com/restaurant',
                success: function(orders){
                    orders = JSON.parse(orders);
                    for (var key in orders) {
                        var obj = orders[key];
                       for (var prop in obj) {
                          //do your append code here
                        }
                    }
                    /*$.each(orders, function(i, order){
                        $orders.append('<li>name: ' + order.name + '</li>');
                    });*/
                }
            });
        });

        $('#add-rest').on('click', function(){
            var order = {
                name: $name.val(),
            };

            $.ajax({
                type: 'POST',
                url: 'http://testing-sh1.appspot.com/restaurant',
                data: order,
                success: function(newOrder){
                    newOrder = JSON.parse(newOrder);
                    $orders.append('<li>name: ' + newOrder.name +', password: '+ newOrder.password + '</li>');
                }
            });
        });

    </script>

【讨论】:

    【解决方案3】:

    只是对 CORS 的一个想法,您可以查看这篇文章,但大多数时候您已经知道,因为您必须设置服务器来支持: Detect browser support for cross-domain XMLHttpRequests? 你设置服务器了吗?

    【讨论】:

      【解决方案4】:

      您的服务器出现错误 我只是调用 API

      <html>
        <head>
          <title>Internal Server Error</title>
          <style>
            body {
              padding: 20px;
              font-family: arial, sans-serif;
              font-size: 14px;
            }
            pre {
              background: #F2F2F2;
              padding: 10px;
            }
          </style>
        </head>
        <body>
          <h1>Internal Server Error</h1>
          <p>The server has either erred or is incapable of performing
          the requested operation.</p>
          <pre>Traceback (most recent call last):
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py&quot;, line 1535, in __call__
          rv = self.handle_exception(request, response, e)
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py&quot;, line 1529, in __call__
          rv = self.router.dispatch(request, response)
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py&quot;, line 1278, in default_dispatcher
          return route.handler_adapter(request, response)
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py&quot;, line 1102, in __call__
          return handler.dispatch()
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py&quot;, line 572, in dispatch
          return self.handle_exception(e, self.app.debug)
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py&quot;, line 570, in dispatch
          return method(*args, **kwargs)
        File &quot;/base/data/home/apps/s~testing-sh1/1.391270213179374270/restaurant.py&quot;, line 29, in post
          key = new_restaurant.put()
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py&quot;, line 3451, in _put
          return self._put_async(**ctx_options).get_result()
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py&quot;, line 342, in get_result
          self.check_success()
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py&quot;, line 386, in _help_tasklet_along
          value = gen.throw(exc.__class__, exc, tb)
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/context.py&quot;, line 824, in put
          key = yield self._put_batcher.add(entity, options)
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py&quot;, line 389, in _help_tasklet_along
          value = gen.send(val)
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/context.py&quot;, line 358, in _put_tasklet
          keys = yield self._conn.async_put(options, datastore_entities)
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/datastore/datastore_rpc.py&quot;, line 1852, in async_put
          pbs = [entity_to_pb(entity) for entity in entities]
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py&quot;, line 697, in entity_to_pb
          pb = ent._to_pb()
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py&quot;, line 3158, in _to_pb
          self._check_initialized()
        File &quot;/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py&quot;, line 3014, in _check_initialized
          'Entity has uninitialized properties: %s' % ', '.join(baddies))
      BadValueError: Entity has uninitialized properties: name
      </pre>
        </body>
      </html>
      

      现在我发送一个名字,响应是

      {
      "reviews": [0]
      "name": "testing"
      "key": 5722646637445120
      }
      

      您需要从您的 ajax 调用中更改这部分`

      var order = $name.val();
      
      
          $.ajax({
              type: 'POST',
              url: 'http://testing-sh1.appspot.com/restaurant',
              data: {name:order},
              success: function(newOrder){
                  $orders.append('<li>name: ' + newOrder.name + '</li>');
              }
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多