无法使用 AJAX 和 jQuery 将 POST 到 my API

Unable POST to my API with AJAX & jQuery

本文关键字:POST my API jQuery AJAX      更新时间:2023-09-26

我是jQuery和javascript的新手,真的很难POST和GET到我的API。当我通过 git bash 命令行发出卷曲请求但无法通过 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 只是为了测试。希望第二双眼睛可以帮助我。谢谢你们的帮助。

你有一个错别字,在

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

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

我得到了"测试"的响应

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

我直接测试了 AJAX。

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

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

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>

只是关于 CORS 的一个想法,你可以查看这篇文章,但大多数时候你已经知道了,因为你必须设置服务器来支持:检测浏览器对跨域 XMLHttpRequest 的支持?是否设置了服务器?

您的服务器中有错误我只是进行 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>');
        }
    });