参数“&"中断$ .ajax请求 [英] Parameter with '&' breaking $.ajax request

查看:78
本文介绍了参数“&"中断$ .ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Web应用程序,该Web应用程序在客户端使用JavaScript + JQuery,在服务器端使用PHP.

I'm developing a Web App that uses JavaScript + JQuery on the client side and PHP on the server side.

我要作为AJAX请求的参数传递的字符串之一具有'&'在其内容中.

One of the strings I want to pass as parameter for an AJAX Request has a '&' in its content.

因此,请求的字符串已损坏.浏览器认为"该参数已结束,因为存在&"在字符串上.

For this reason, the string of the request is broken. The browser "thinks" that this parameters is over because there is a '&' on the string.

var hasChar = "This is a string that has a & in the content.";
var doesntHave = "This one does not contain.";
var dataString = "first=" + hasChar + "&second=" + doesntHave;

$.ajax({
    type : "POST",
    url : "myurl.php",
    data : dataString,
    cache : false,
    success : function(html) {
    }
});

服务器收到的第一个参数为这是一个带有"

The server receives the first parameter as "This is a string that has a "

我的问题:

如何在客户端对字符串进行编码以及如何在PHP服务器上对其进行解码.

How to I encode the string on the client side and how should I decode it on the PHP server.

推荐答案

为什么不执行以下操作:

Why not to do following:

    $.ajax({
        type : "POST",
        url : "myurl.php",
        data : {
          'first': hasChar,
          'second': doesntHave
        },
        cache : false,
        success : function(html) {
        }
    });

在这种情况下,jQuery将确保正确编码字符串.

In this case jQuery will make sure that string is properly encoded.

作为替代方案,您可以使用encodeURIComponent()JS的内置函数来正确编码字符串:

As an alternative you can use encodeURIComponent() JS's built in function for properly encoding strings:

var dataString = "first=" + encodeURIComponent(hasChar) + "&second=" + encodeURIComponent(doesntHave);

这篇关于参数“&"中断$ .ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆