【问题标题】:call c# logic from external javascript file [duplicate]从外部javascript文件调用c#逻辑[重复]
【发布时间】:2017-02-07 07:04:12
【问题描述】:

我是 javascript 的新手,我有一个问题,我有一个外部 js 文件,我需要运行一些 c# 服务器端代码。我的外部 js 文件类似于:

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 做点什么

【问题讨论】:

  • 你是否包含了 jquery($ 实现)??
  • 那是什么,我不知道。你能解释一下吗?

标签: javascript c# ajax xmlhttprequest


【解决方案1】:

您缺少 jquery 参考文件,从下面的链接下载它并在您的 html 文件中引用它。在 src 中,您需要编写 jquery.min.js 文件的路径。如果它与您的 html 文件位于同一文件夹中,请使用以下代码

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

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

【讨论】:

  • 没有html文件,这是其他项目可以引用和使用的脚本,我不访问那些项目它们是外部项目
  • 我需要对那个外部 js 文件做点什么
  • 在那个外部js文件中添加这个函数(function() { // Load the script 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文件后不会出现$错误。
【解决方案2】:

您可以在没有jQuery 的情况下执行 AJAX 请求。您所需要的只是修复您的 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 上找到更多示例。

【讨论】:

  • 对不起,我对 js 很陌生,我不知道如何确定根据控制器响应显示警报窗口,我应该把那个逻辑放在哪里?
  • @someone 进入我的示例顶部的reqListener 函数。
  • 当我用断点按 f12 时,我看到 reqListener() 函数永远不会运行,当我在 xhReq.addEventListener("load", reqListener) 之后添加 () 它运行但 responsText 未定义: (
  • @someone 我认为您的请求有误。我更新了我的答案。请参阅有关错误处理的部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多