2013-02-21 73 views
0

這真的很奇怪,我不知道自己出錯的地方。

這裏是我的控制器:

namespace MvcAJAX.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ActionResult Index() 
     { 
      return View(); 
     }   

     public ActionResult Called() 
     { 
      var retObject = new { rollNo = 2, name = "Deepanjan" }; 
      return Json(retObject); 

     } 
    }  
} 

這裏是我的索引視圖:

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 
<script> 
    /// <reference path="~/Scripts/jquery-1.7.1.js" /> 
    $(document).ready(function() { 
     $('#button1').click(function() { 
      $.getJSON("/Home/Called",function() { 
       alert('Working!'); 
       $('#p1').text("Roll Number was " + data.rollNo + " and the Name was " + data.name); 
      }); 
     }); 
    }); 
</script> 
<h1>This page demos Load with callback function!</h1> 
<input type="button" id="button1" value="Click Me!"/><br /> 
<p style="height:200px" id="p1"></p> 
<hr /> 

我的getJSON根本不起作用&我甚至不得到警報。怎麼了?

+0

檢查您的瀏覽器控制檯是否有任何錯誤。你有沒有檢查點擊事件是否被調用? – 2013-02-21 11:26:37

+1

試着用'return Json(retObject,JsonRequestBehavior.AllowGet)替換'return Json(retObject);''' – 2013-02-21 11:41:06

回答

1

你在哪裏包括jQuery的文件? jquery文件首先要比你自己的JavaScript代碼寫得更多。

並嘗試使用此代碼;

$(document).ready(function() { 
    $('#button1').click(function() { 
     $.getJSON("/Home/Called", function (retObject) { 
      alert('Working!'); 
      $('#p1').text("Roll Number was " + retObject.rollNo + " and the Name was " + retObject.name); 
     }); 
    }); 
}); 

嘗試替換return Json(retObject);return Json(retObject,JsonRequestBehavior.AllowGet);

1

嘗試從視圖中的Ajax後,像這樣的

 
$.ajax({ 
url: '@Url.Action(action)', 
    data: data 
    type: 'POST', 
    success: function (result) { 

           } 
          }); 
0

***>只在你的MVC控制器功能在此線

Configuration.ProxyCreationEnabled = FALSE;