2016-09-29 78 views
0

我很新的JavaScript,我有一個問題,我有一個外部js文件,我需要運行一些c#服務器端代碼。我的外部js文件是一樣的東西:從外部JavaScript文件調用c#邏輯

my.login = function(parameter, callback) { 
    if(someCondition) 
    { 
     alert("you cant progress") 
    } 
    else 
    { 
     //not importent logic 
    } 
} 

我認爲兩種方式與Ajax調用準備他們的一些條件之一:

$.get("locallhost:2756/myCont/MyAct?Id=" + Id + "", function(response) { 
    if (!response.result) { 
     alert("you cant progress"); 
    } 

,但我得到另一種選擇是錯誤$沒有定義 使用XMLHttpRequest來是這樣的:

var xhReq = new XMLHttpRequest(); 
xhReq.open("POST", "locallhost:2756/myCont/MyAct?Id=" + Id + "", true); 
xhReq.send(Id); 
var res = xhReq.response; 
var stat= XMLHttpRequest.status; 
var resText= xhReq.responseText; 

,但我什麼也沒得到在resText其「」, 我的控制器和動作也是這樣的:

public class myContController : Controller 
{  

    [HttpPost] 
    public JsonResult MyAct(string Id) 
    { 
     if (Logic.ValidateId(Id)) 
     { 
      return Json(new { result = true }); 
     }; 
     return Json(new { result = false }); 
    } 
} 

我要的是在C#中驗證的東西,如果它好不好結果返回到JavaScript中,如果有另一種方式,你能幫我嗎?

編輯: 我知道我可以在html文件中引用jquery,以避免$未定義,但這是外部js,其他人可以使用它,它們不在我的項目中。我需要做的東西與外部js

+0

你有包括jQuery($執行)? –

+0

那是什麼,我不知道。你能解釋更多嗎? – someone

回答

2

你錯過了jquery參考文件從下面的鏈接下載並引用它在你的html文件。在src中,您需要編寫jquery.min.js文件的路徑。如果在同一文件夾作爲HTML文件使用下面的代碼

<script src="jquery.min.js"></script> 

鏈接:http://jquery.com/download/

+0

沒有html文件,這是一個腳本,其他項目可以引用它並使用它,我不訪問那些項目,他們是外部項目 – someone

+0

我需要做一些外部js文件 – someone

+0

在該外部js文件添加此函數'(function(){ //加載腳本 var script = document.createElement(「SCRIPT」); script.src ='https://ajax.googleapis.com/ajax/libs/jquery/1.7。 1/jquery.min.js'; script.type ='text/javascript'; document.getElementsByTagName(「head」)[0] .appendChild(script); })();'附加jquery文件後你不會得到$錯誤。 – Iqbal

1

你可以做AJAX請求,而不jQuery。所有你需要的是解決您XMLHttpRequest用法:

function reqListener() { 
    console.log(this.responseText); 
}; 

function errListener() { 
    console.log(this.responseText); 
}; 

var xhReq = new XMLHttpRequest(); 
xhReq.addEventListener("load", reqListener); 
xhReq.addEventListener("error", errListener); // this works for errors 
xhReq.open("POST", "locallhost:2756/myCont/MyAct?Id=" + Id + "", true); 
xhReq.send(Id); 

你也可以添加其他的回調。

你可以在MDN找到更多的例子。

+0

我是sry我對js非常陌生我不知道如何確定顯示基於控制器響應的報警窗口,我應該在哪裏放置該邏輯? – someone

+0

@someone到我的例子頂部的'reqListener'函數中。 – feeeper

+0

當我按f12斷點我看到reqListener()函數永遠不會運行,當我加入()後在xhReq.addEventListener(「加載」,reqListener)它運行但responsText未定義:( – someone