簡體   English   中英

如何將值從javascript發送到服務器端(asp.net)?

[英]how to send values from javascript to server side(asp.net)?

在不刷新頁面的情況下將值從JavaScript(客戶端)發送到服務器(asp.net)的最佳方法是什么?

我想將數據插入數據庫,但是我不想刷新頁面或更改頁面上的任何數據。

簡單方法:

1-將jQuery導入您的頁面
2-這樣在頁面的cs文件中創建ur函數

     [WebMethod]
    public static string Save(string param1,string param2)
    {
        string result;
        //your code must return somthing string
        return result;
    }

3-在aspx頁面中創建函數

function save(){
var param1 = 'value 1 you need to send to the server should be string';
var param2 = 'value 2 you need to send to the server should be string';
         $.ajax({
                  type: "POST",
                  url: "pagename.aspx/Save",
                  data: "{param1: '"+ param1 +"' , param2 :'"+ param2 +"'}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  async: false,
                  cache: false,
                  success: function(result){
                 //Successfully gone to the server and returned with the string result of the server side function do what you want with the result  

                  }
                  ,error(er)
                  {
                  //Faild to go to the server alert(er.responseText)
                  }
          });
        }

4-點擊按鈕調用此功能

對於我的代碼和腳本的更多問題或描述,我在這里:)

一種簡單的方法是在頁面上使用頁面方法或靜態方法,並使用jquery從服務器端代碼發送或獲取數據。 該鏈接有一個很好的演練

http://encosia.com/using-jquery-to-direct-call-aspnet-ajax-page-methods/

實際上沒有人回答這個問題。 如“導入jquery”,“使用ajax”等都否定了OP要求使用JavaScript解決方案的事實。 這是javascript的單行代碼,非常容易做到。

在您的JavaScript中,您只需調用方法:

PageMethods.SomeMethod('test');

您的“ SomeMethod”將是這樣的方法背后的代碼:

[WebMethod]
    public static string SomeMethod(string param1)
    {
        string result = "The test worked!";
        return result;
    }

規則:您必須使用WebMethod屬性標識方法后面的代碼。 它必須是靜態的。 並且您必須在頁面中注冊腳本管理器,如下所示:

<asp:ScriptManager ID="MyScriptManager" runat="server" EnablePageMethods="true" />

由於我正在使用aspx Webforms頁面執行一些非常簡單的javascript函數,例如檢索/隱藏地理位置,因此,我根據需要將其放在Form元素中。

該技術稱為Ajax ,不乏教程 (更不用說對大庫(如YUIjQuery )的支持)。

Ypu必須使用Ajax技術, JQueryAsp.netYUI以及其他使您可以使用Ajax技術的api和庫。

Asp.net中最簡單的一種是通過向頁面添加ScriptManagerUpdatePanel來使用內置的Asp.net Ajax功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM