如何限制jquery中的字符串字符数

时间:2015-01-27 17:19:42

标签: php jquery ajax

我试图通过Ajax帖子将此文本Montréal-Pierre Elliott Trudeau International Airport, Montreal, QC, Canada发送到php脚本。我在尝试发送文本中的所有字符时收到500 (Internal Server Error)

当我通过手动编码尝试'Montréal-Pierre-Elliott-Trudeau-International'时,它有效。

这是我的ajax脚本

$("#nomination-name").focus(function(){
        $.post(
            '/getlocation/'+$("#newLatitude").val()+"/"+$("#newLongitude").val()+"/"+'ok', // location of your php script
            { place: 'Montréal-Pierre-Elliott-Trudeau-International'}, // any data you want to send to the script
            function( data ){  // a function to deal with the returned information


    $(".flickr-images").remove();
            for(i=0;i<data.images.length;i++) {
                $("#images").append(data.images[i]);
            }
        });
});

这是服务器脚本:

public function getLocationImage($latitude, $longitude, $cc){

            //$place = 'Montreal, Pierre, Elliott, Trudeau, International, Airport';
            //GET THE IMAGES BASED ON THE LOCATION FROM FLICKR.
            $api_key = 'my_api_key';
            $text  = Input::get('place');
           // $text = 'airport';
            $lat = '&lat='.$latitude;
            $lon = '&lon='.$longitude;
            $perPage = 6;
            $url = 'https://api.flickr.com/services/rest/?method=flickr.photos.search';
            $url.= '&api_key='.$api_key;
            $url.= '&text='.$text;
//            $url.= $lat;
//            $url.= $lon;
            $url.= '&per_page='.$perPage;
            $url.= '&format=json';
            $url.= '&nojsoncallback=1';
            $response = json_decode(file_get_contents($url));
            $photo_array = $response->photos->photo;

            $count=0;
            foreach($photo_array as $single_photo){
                $size = 's';
                $size2='b';
                $photo_url = 'https://farm'.$single_photo->farm.'.staticflickr.com/'.$single_photo->server.'/'.$single_photo->id.'_'.$single_photo->secret.'_'.$size.'.'.'jpg';
                $photo_url_big = 'https://farm'.$single_photo->farm.'.staticflickr.com/'.$single_photo->server.'/'.$single_photo->id.'_'.$single_photo->secret.'_'.$size2.'.'.'jpg';

                $img[$count] = "<a href='$photo_url_big' target='_blank'><img class='flickr-images' title='' src='$photo_url' /></a>";
                $count++;
            }



            return Response::json(["success"=>"true", "images"=>$img]);


    }

我试图删除字符串中的空格和逗号并将其数量限制为20.我尝试了以下方法但是不对。

$('#geocomplete').val().replace(/[, ]+/g, "-").substr(20, $('#geocomplete').val().replace(/[, ]+/g, "-").length)

这是正确的方法吗?

2 个答案:

答案 0 :(得分:1)

您需要对参数进行编码:

$url.= '&text='.urlencode($text);

答案 1 :(得分:0)

var data = $('#geocomplete').val().substr(0,20); //get the first 20 characters
data.replace(/\s+/g, '-'); //replace all spaces with '-'