【问题标题】:How to put & in in URL with jQuery.load?如何使用 jQuery.load 将 & 放入 URL 中?
【发布时间】:2014-08-28 11:39:07
【问题描述】:

我有一个 Wordpress 页面,它应该使用 jQuerys 加载方法从服务器加载一些代码:

<div id="mydiv"></div>
<script>
jQuery("#mydiv").load("http://localhost/testserver/wp-content/plugins/myplugin/scripts/view/test.php?x=1&amp;y=2&amp;z=3");
</script>

我的 test.php 脚本是:

<?php error_log(var_export($_GET,true)); ?>

但我无法在test.php脚本中正确获取参数x、y、z:错误日志中的输出显示:

'x' => '1',
'amp;y' => '2',
'amp;z' => '3',

(如果我在 url 字符串中使用 x=1&y=2&z=3,我只会在错误日志中得到 'x' => '1')。

我做错了什么或者这可能是 Wordpress 或 jQuery 错误?

【问题讨论】:

  • 你为什么使用 &?只需使用 &。
  • 它是 &amp 不是 amp 'amp;y' => '2',
  • 就像我说的,当我只使用 & 时,我只会在错误日志中得到 'x' => '1'。

标签: jquery wordpress load ampersand


【解决方案1】:

使用encodeURIComponent();

例子

var url = "http://localhost/testserver/wp-content/plugins/myplugin/scripts/view/test.php?x=1&y=2&z=3"
url = encodeURIComponent(url);

jQuery("#mydiv").load(url);

或者使用 .get()

jQuery.get('http://localhost/testserver/wp-content/plugins/myplugin/scripts/view/test.php', {x: 1, y:2, z:3}, function(r){
   jQuery("#mydiv").html(r);
});

【讨论】:

  • 谢谢。接受,因为这更准确地回答了我的问题,但是我认为我更喜欢 Zeto 的方法。
  • 实际上,我接受这个答案的速度太快了。我无法让它在 Wordpress 中工作,尽管它可能在其他设置中工作(这里给出了相同的答案:stackoverflow.com/questions/3741672/…)所以我必须接受 Zeto 的回答。无论如何,谢谢。
【解决方案2】:

http://api.jquery.com/load/

示例:将数据数组传递给服务器。

$( "#objectID" ).load( "test.php", { "choices[]": [ "Jon", "Susan" ] } );

【讨论】:

  • 谢谢!数据将在 $_POST 变量中结束,这是可取的。因此,在我的示例中,数据将发送为:{x:"1",y:"2",z:"3"} 并输出为:error_log(var_export($_POST,true));
猜你喜欢
  • 1970-01-01
  • 2022-12-21
  • 2017-08-22
  • 2012-09-24
  • 1970-01-01
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多