【问题标题】:AJAX call to rest service to post the data from HTML formAJAX 调用休息服务以从 HTML 表单发布数据
【发布时间】:2022-01-25 23:00:30
【问题描述】:
<html>

<body>
    <form method="POST">
        <label>username</lable>
            <input id="username" name="username" type="text">
            <label>emailid</lable>
                <input id="emailid" name="emailid" type="text">
                <button id="enter" type="submit">submit</button>
    </form>
    <script type="text/javascript">
        $(document).ready(function () {
            var userName = $("#username").val();
            var emailId = $("#emailid").val();
            $($enter).click(function () {
                $.ajax({
                    type: 'POST',
                    url: ".....rest service url....",
                    dataType: JSON,
                    data: {
                        "UserName": userName,
                        "EmailId": emailId
                    },
                    success: function (data) {
                        alert("success");
                    }
                    error: function (e) {
                        alert("error" + e)
                    }
                });
            });
        });
    </script>
</body>

</html>

我正在尝试在需要 JSON 响应的休息服务中发布表单字段。 我收到警告错误消息(对象 Object)

我不知道错误在哪里。

【问题讨论】:

  • Object 对象不是错误,它只是告诉你传递给 alert() 的数据类型
  • 但它没有将数据发布到服务中
  • 将 alert("error"+e) 替换为 alert(e.Message) 以便我们知道失败时的实际错误消息是什么
  • 没有.Message方法可以调用!!
  • 有,它是 e(错误)对象的一个​​属性 :)

标签: javascript jquery ajax rest post


【解决方案1】:

你可以试试 $.post 而不是 $.ajax

$.post( "your url",{ UserName: userName, EmailId: emailId }, function( data ){
alert("Success");
});

只需确保您传递的参数与您的 REST 服务相匹配。

【讨论】:

  • 您的 REST 服务是否按预期返回数据?
【解决方案2】:
$($enter).click(function () {

这部分代码看起来无效,请为点击函数提供正确的选择器。

【讨论】:

    【解决方案3】:

    首先改变这个 $($enter).click(function to $("#enter").click(function () { 您确定您为此任务编写的服务是后期服务吗...有时我会犯错误,例如发布数据并为获取数据而编写服务。如果您可以展示您的服务结构,这将有助于获得更好的洞察力。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-24
      • 2016-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-15
      相关资源
      最近更新 更多