欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

如何利用jQuery post傳遞含特殊字符的數(shù)據(jù)

 更新時(shí)間:2015年10月19日 09:35:26   作者:大濤哥  
在jquery中,解決數(shù)據(jù)傳遞處理的方法我們通常利用$.ajax或$.post,但是這里這里通常不能傳遞特殊字符,比如說:“<”,本文就幫大家解決如何傳遞這種含特殊字符的數(shù)據(jù),感興趣的朋友一起看下吧

在jQuery中,我們通常利用$.ajax或$.post進(jìn)行數(shù)據(jù)傳遞處理,但這里通常不能傳遞特殊字符,如:“<”。本文就介紹如何傳遞這種含特殊字符的數(shù)據(jù)。

    1、準(zhǔn)備頁(yè)面和控制端代碼

    頁(yè)面代碼如下:

<script type="text/javascript">
  $(function() {
      $("#btnSet").click(function() {
        var a = $("#txtValue").val();
        var data = { Name: a };
        alert(data);
        $.ajax({
          url: '@Url.Action("MyTest")',
          type: 'post',
          dataType: 'json',
          data: data,
        });
      });
    }
  );
</script>
<h2>Index</h2>
<input type="text" id="txtValue"/><input type="button" value="設(shè)置" id="btnSet"/>

    后臺(tái)代碼如下:

  public ActionResult MyTest(StudentInfo stu)
    {
      return Content("OK");
    }

其中StudentInfo定義如下:

  public class StudentInfo
  {
    public string Name { get; set; }
  }

    2、測(cè)試數(shù)據(jù)傳遞

    當(dāng)我們傳遞普通數(shù)據(jù)時(shí),一切正常。

    但當(dāng)輸入含特殊字符的數(shù)據(jù)時(shí),不能正常傳遞到后臺(tái)。

    3、處理方法

    如果確定要傳遞特殊字符,需要對(duì)jQuery代碼作調(diào)整,調(diào)整后的請(qǐng)求代碼如下:

<script type="text/javascript">
  $(function() {
      $("#btnSet").click(function() {
        var a = $("#txtValue").val();
        var data = JSON.stringify({ Name: a });
        alert(data);
        $.ajax({
          url: '@Url.Action("MyTest")',
          type: 'post',
          dataType: 'json',
          data: data,
          contentType: 'application/json'
        });
      });
    }
  );
</script>

    調(diào)整的地方主要有兩點(diǎn):

對(duì)要傳遞的json數(shù)據(jù)作序列化JSON.stringify
在$.ajax請(qǐng)求中新增參數(shù):contentType:'application/json'

好了,以上就是本文的全部所述,希望大家喜歡。

相關(guān)文章

最新評(píng)論