weixin_33728268 2017-05-02 07:12 采纳率: 0%
浏览 117

MVC控制器返回JSON

I have this HTML and script :

<form>
    Text :<br>
    <input type="text" name="nameid" id="nameid" value="">
    <br><br>
    <input type="submit" value="Send">
</form> 

$(document).ready(function () {

    $("form").submit(function (event) {
        $.ajax({
            type: 'GET',
            url: "/MyController/MyAction2",
           data: { nameid: $('#nameid').val() },
            success: function (newdata) {
                var cy = cytoscape({
                    container: document.getElementById("cy"),
                    elements: JSON.parse(newdata)

                });
                });
            }
        });

    });

});

When MyAction2 is called from AJAX, the url goes to MyAction2 and I see raw JSON data. How can I make MyAction2 returns value to the AJAX and I would use it as newdata variable? Thanks.

  • 写回答

1条回答 默认 最新

  • 旧行李 2017-05-02 07:16
    关注

    The code you've used to get JSON data is correct, you just need to stop the form submission, which you can do by calling preventDefault() on the event.

    Also note that you have a mis-matched }); in the question but I assume this is just a typo in the question itself. Also note that you don't need to manually JSON.parse the response if you set the correct dataType. Try this:

    $(document).ready(function () {
      $("form").submit(function (event) {
        event.preventDefault(); // < add this...
    
        $.ajax({
          type: 'GET',
          url: "/MyController/MyAction2",
          data: { nameid: $('#nameid').val() },
          dataType: 'json', 
          success: function (newdata) {
            var cy = cytoscape({
              container: document.getElementById("cy"),
              elements: newdata
            });
          }
        });
      });
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler