php laravel中的转义单引号



我在位置数据库中有一个地址字段,值为Shop 2197 - Block 1014 - Road 90 - Al-Delaa' Complex - Hamala,网站运行良好,直到我添加了带有此地址的位置,谷歌地图插件不再工作,因为这句话在控制台中导致了javascript错误

我的位置控制器获取功能:

public static function get() {
$locations = Location::with('country')->get();
return $locations;
}

将位置加载到谷歌地图的脚本:

var locations = JSON.parse('{!! $locations !!}');
var lang = "{{ App::getLocale() }}";
$(locations).each(function(key, value) {
allLocationsPins.push({lat: parseInt(value.latitude), lng: parseInt(value.longitude)});
});

地址值中的单引号导致了此错误,因为它没有转义。在从控制器返回函数之前,我尝试将JSON encode函数添加到locations数组中,但没有发生任何事情。我认为,由于脚本文件中的{!!$locations!!},用Json_encode转义单引号是不起作用的,但如果我尝试删除字符串中的每一个字符都会发生变化。

我该怎么解决这个问题?如果json_encode不工作,我还能用什么?

我试图在forloop中的单引号之前添加\,但由于某种原因,它什么都没做,这是forloop和输出。

public static function get() {
$locations = Location::with('country')->get();
foreach ($locations as $location) {
$location["address"] = str_replace("'","'",$location["address"]);
}
var_dump($locations);
return $locations;
}

// PART OF VAR DUMP OUTPUT..
array(14) {
["id"]=>
int(7)
["title"]=>
string(6) "Hamala"
["title_ar"]=>
NULL
["address"]=>
string(62) "Shop 2197 - Block 1014 - Road 90 - Al-Delaa' Complex - Hamala"
["address_ar"]=>
NULL
["latitude"]=>
string(9) "26.166246"
["longitude"]=>
string(9) "50.468510"
["phone_numbers"]=>
string(13) "+973 17610612"
["customer_service_email"]=>
string(28) "Marketing@aljasser-group.net"
["working_hours"]=>
string(84) "From 09:00 AM to 01:00 PM | Evening Shift: From 04:00 PM to 08:00 PM | Friday is off"
["working_hours_ar"]=>
NULL
["country_id"]=>
int(3)
["created_at"]=>
string(19) "2017-11-13 16:21:15"
["updated_at"]=>
string(19) "2017-11-06 19:01:54"
}
["original":protected]=>
array(14) {
["id"]=>
int(7)
["title"]=>
string(6) "Hamala"
["title_ar"]=>
NULL
["address"]=>
string(61) "Shop 2197 - Block 1014 - Road 90 - Al-Delaa' Complex - Hamala"
["address_ar"]=>
NULL
["latitude"]=>
string(9) "26.166246"
["longitude"]=>
string(9) "50.468510"
["phone_numbers"]=>
string(13) "+973 17610612"
["customer_service_email"]=>
string(28) "Marketing@aljasser-group.net"
["working_hours"]=>
string(84) "From 09:00 AM to 01:00 PM | Evening Shift: From 04:00 PM to 08:00 PM | Friday is off"
["working_hours_ar"]=>
NULL
["country_id"]=>
int(3)
["created_at"]=>
string(19) "2017-11-13 16:21:15"
["updated_at"]=>
string(19) "2017-11-06 19:01:54"
}

正如你所看到的,地址位置数组是两次找到的,第一次是按预期更改的,第二次是受保护的,没有更改,问题是这里的

["address"]=>
string(61) "Shop 2197 - Block 1014 - Road 90 - Al-Delaa' Complex - Hamala"

如果字符串只有一个引号,则传递给JSON.parse()的字符串变量将无法工作,因为该方法不接受它们。

在解析'{!! $locations !!}'之前,先尝试将其声明为变量,看看这是否有效,不应该。

您将不得不手动用""转义单引号

示例:

var aString = '{ "name":"John", "age":30, "city":"New'York"}'
var aJson = JSON.parse(aString)

最新更新