开发者

Special characters break json returned to jQuery

The following jQuery ajax function runs a PHP script that queries a MySQL database containing entries that are encoded as UTF-8:

function searchLocations() {

    var stateSelected = $("#stateSelect").val();

    $.ajax({
        url: 'ajax/json.php',
        dataType: 'json',
        data: 'state='+stateSelected,
        success: function(data) {
            placeMarkers(data.markerdata.markers);
        }
    });

}

The JSON object returned to the function contains the longitudes and latitudes of map marker obje开发者_开发知识库cts as well as a name to display in an info window when each marker is clicked.

Every name loads fine, and is displayed without a problem except for a single name which contains the character "ñ". This name is returned in the JSON object as "null". How can I make this name display properly?


I used to have this problem and I found there was two options:

  1. In PHP convert all characters into HTML friendly characters using the PHP function htmlentities (http://php.net/manual/en/function.htmlentities.php) before returning it to the jQuery function.
  2. If that fails or the characters are not converted you could try using base64 encode and decode. In PHP you can encode the data using base64_encode function (http://php.net/manual/en/function.base64-encode.php). Then in jQuery you could use one of many base64 encode and decode plugins to decode the data. I have used this plugin successfully in the past: http://plugins.jquery.com/project/base64-encode-and-decode

Failing both those options it may be worth looking at the character set used by your page. Try and use UTF-8 to encode your HTML and see if that helps.

Without using jQuery and AJAX if you did a basic PHP page that queried the data in question and prints the name out does it still not display correctly. If it doesn't it could also be a character set issue with MySQL.

Hope any of these pointers help. Let me know how you get on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜