JS請求伺服器,並返回資訊,請求過程中不需要跳轉頁面

來源:互聯網
上載者:User

標籤:style   blog   http   color   java   os   io   strong   檔案   

js請求伺服器,並返回資訊,請求過程中不需要跳轉頁面

這個可以通過jQuery架構輕鬆實現,jQuery中包含多種ajax的請求方式,詳細可以參考下對應 的API。

你上面定義的按鈕類型是submit,如果是在form當中,將會自動認可當前form表單,建議,如果可能的話將其修改為button類型。

下面給出通過jQuery的$.post方式,非同步擷取伺服器的JSON資料。

功能代碼:

<script type="text/javascript">    $(function(){        // 定義存放伺服器傳回值的變數        var jsonData = null;        $(‘#submitBtn‘).click(function(){            // 請求的參數            var params = {};            $.post(‘json.json‘, params, function(data){                // 這裡data就是返回的JSON對象                jsonData = data;                alert(jsonData.name);            }, ‘json‘);        });    });</script>

完整代碼:

<html><head><style></style><meta http-equiv="Content-Type" content="text/html; charset=GBK"><script type="text/javascript" src=" <script type="text/javascript">    $(function(){        // 定義存放伺服器傳回值的變數        var jsonData = null;        $(‘#submitBtn‘).click(function(){            // 請求的參數            var params = {};            $.post(‘json.json‘, params, function(data){                // 這裡data就是返回的JSON對象                jsonData = data;                alert(jsonData.name);            }, ‘json‘);        });    });</script></head><body><div>    <input type="button" value="提交" id="submitBtn"/></div></body></html>

 json.json檔案內容:

{    "name" : "Steven",    "sex"  : "Male",    "age"  : 10}

 

JS請求伺服器,並返回資訊,請求過程中不需要跳轉頁面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.