【问题标题】:How can I post the data that coming from Ajax? [closed]如何发布来自 Ajax 的数据? [关闭]
【发布时间】:2021-07-30 15:29:19
【问题描述】:

我的脚本代码如下。在这里,如何保存我收到的 exits_response 数据作为对控制器中数据库的响应?在后操作结果中,参数“变量”为空。当 ajax 中没有邮政编码时,响应返回并显示“exist_response”。我没有写注册到控制器的过程,因为我在发布时得到了空数据。

我解决了问题,我错误地定义了数据变量。

js 代码

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js%22%3E</script>
        <script type="text/javascript">
    $('#submit').click(function (event) {
        event.preventDefault();

        var exist_response = $.ajax({ type: "GET", url: "https://heroku-diagnosis.herokuapp.com/predict", data: "Symptom_1=" + $('#Symptom_1').val() + "&Symptom_2=" + $('#Symptom_2').val() +
            "&Symptom_3=" + $('#Symptom_3').val() + "&Symptom_4=" + $('#Symptom_4').val() + "&Symptom_5=" + $('#Symptom_5').val() + "&Symptom_6=" +
            $('#Symptom_6').val() + "&Symptom_7=" + $('#Symptom_7').val() + "&Symptom_8=" + $('#Symptom_8').val() + "&Symptom_9=" + $('#Symptom_9').val() + "&Symptom_10=" + $('#Symptom_10').val() +
            "&Symptom_11=" + $('#Symptom_11').val(),async: false}).responseText;
             $('#output').text("According to the symptoms you have entered, you may have a " +exist_response + " disease. Make an appointment on our website to consult a doctor. " );

           $.ajax({
        type:"POST",
        url:"/Prediction/Index",
        data: { variable: exist_response },
        success: function(response){
           alert(response);
        }});



        </script>

控制器

[HttpPost]
    public ActionResult Index(String variable,int id)
    {
        return View();
    }

【问题讨论】:

  • 这篇文章需要更多细节。
  • 对不起,我看不出第一个 ajax 与第二个有什么关系?什么是输出?哪个 ajax 不能正常工作?

标签: c# json ajax asp.net-mvc


【解决方案1】:

你已经有一个字符串了。但是您使用 JSON.stringify(exist_response) 再次对其进行了字符串化。所以你发送了双字符串化对象。 试试这个

$.ajax({
            type:"POST",
            url:"/Prediction/Index",
            data: { variable: exist_response },
            success: function(response){
               alert(response);
            }
});

更新:

如果你想将 Id 发送给控制器,你可以这样做

var id= ...your code;

$.ajax({
          ....
            data: {  variable: exist_response, id: id },
          ...
});

【讨论】:

  • 非常感谢谢尔盖。它现在可以工作了,但是代码出了什么问题你能和我分享一下原因吗? @Sergey
  • 不客气。我在答案中添加了一些 cmets。
  • 我需要在 Controller 部分中使用exist_response 发送我的模型的ID。我重新安排了问题的控制器部分。如何发送模型 ID?
  • @learningwoman 我更新了我的答案。请尝试
  • 我做到了,你是最棒的! @Sergey
【解决方案2】:

要通过 ajax 发布请求正确地将数据传递给控制器​​方法,您必须指定“变量”参数名称:

$.ajax({
    type:"POST",
    url:"/Prediction/Index",
    data: { variable: JSON.stringify(exist_response) },
    dataType: "json",
    success: function(response){
       alert(response);
    }
});

已经回复here

【讨论】:

  • @BorishSh 当我们这样做时,我们的第一个带有 get 的 ajax 不起作用,它再次变为 null。
  • @learningwoman 只需删除 dataType: "json" 和 stringify,这个 ajax 就可以正常工作了
猜你喜欢
  • 2019-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-10
  • 1970-01-01
  • 2017-01-06
  • 1970-01-01
相关资源
最近更新 更多