【问题标题】:Calling php scripts with parameters and setting result in viewbag使用参数调用php脚本并在viewbag中设置结果
【发布时间】:2016-08-11 10:27:44
【问题描述】:

我无法从 Java Script 调用 php 脚本,然后使用该结果为我的控制器设置视图包值。 下面是代码:

<script>
var model = '<% = this %>';
var data = { NAMEPARAM: model.name }

$(document).ready(function () {
$("#AlertButton").click(function () {
    $.ajax({
        type: 'POST',
        url: "www/CustomScripts.php",
        data: data
    }).success(function(data) {
        //need to set the returned message in view bag here.
    }).error(function (data) {
         alert("An error occurred while processing request")
        });
    });
});
</script>

<button id ="AlertButton" type="submit" class="btn green"> Alert </button>
<div id="PHPResult"> @ViewBag.message </div>

我上面面临的问题是在我的 ViewBag 中设置返回的成功消息,然后将其显示在屏幕上。我知道如何在 html div 中直接设置结果,但我需要在 Viewbag 中设置它

我将 name 参数传递给 php 脚本的方式也是如此。这是正确的方法,还是有更好的方法来实现?

【问题讨论】:

    标签: javascript php jquery asp.net viewbag


    【解决方案1】:

    我想不出在这里涉及 ViewBag 的理由。您没有对 MVC 进行回发,因此无法填充它。它只是 HTML/Javascript 和 PHP 网络服务之间的事务。

    所以,其实比较简单:

    <script>
    var model = '<% = this %>';
    var data = { NAMEPARAM: model.name }
    
    $(document).ready(function () {
      $("#AlertButton").click(function () {
        $.ajax({
          type: 'POST',
          url: "www/CustomScripts.php",
          data: data
        }).success(function(data) {
         $("#PHPResult").html(data); //assuming "data" is a user-friendly string
        }).error(function (data) {
          alert("An error occurred while processing request")
        });
      });
    });
    </script>
    
    <button id ="AlertButton" type="submit" class="btn green"> Alert </button>
    <div id="PHPResult"></div>
    

    【讨论】:

    • 是的,我知道该怎么做。但是,我面临的问题是在视图包中设置从 php 服务返回的结果。原因是,在控制器内部,我需要根据该结果进行一些操作。所以我的问题是,有没有办法从视图包内的 php web 服务设置结果。即使您可以向我推荐任何链接或帮助材料,也会非常有帮助。
    • 目前您正在将数据直接返回到客户端网页,并完全绕过控制器。您的代码将在您的所有控制器代码完成后运行,并且页面已呈现给用户。它将在用户的机器上运行,而不是在服务器上。要执行您想要的操作,您可以 (a) 将计算代码移动到 javascript 中,或者 (b) 从 C# 代码中调用 PHP 方法 - 为此,这里的第二个答案可能会有所帮助:stackoverflow.com/questions/5512951/…
    猜你喜欢
    • 2018-01-07
    • 1970-01-01
    • 2012-04-06
    • 2011-11-30
    • 2020-06-05
    • 1970-01-01
    • 2017-05-01
    • 2013-02-04
    • 1970-01-01
    相关资源
    最近更新 更多