[英]How to use the ajax() function in JQuery?
In my javascript file I have the following: 在我的javascript文件中,我有以下内容:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'script.php',
data: '',
success: function(output) {
alert(output[0])
}
});
</script>
In my PHP file I have the following: 在我的PHP文件中,我有以下内容:
<?php
echo 'dog';
echo 'cat';
?>
Now I know I'm not passing any data through the ajax function, I just wrote the above to test one thing, that is: 现在我知道我没有通过ajax函数传递任何数据,我只是编写了上面的内容来测试一件事,那就是:
When I alert output[0]
I get the letter "d". 当我提示
output[0]
我得到字母“d”。 Instead I want to be able to get "dog" and when I alert output[1]
I want to be able to get "cat". 相反,我希望能够获得“狗”,当我提醒
output[1]
我希望能够得到“猫”。 How to achieve this? 怎么做到这一点?
By default, given the response your call is receiving, jQuery is simply handing you the output as a string, in which case you'd have to do whatever string splitting/parsing as appropriate. 默认情况下,给定您的调用接收的响应,jQuery只是将输出作为字符串处理,在这种情况下,您必须根据需要执行任何字符串拆分/解析。
See http://api.jquery.com/jQuery.ajax/ and specifically the dataType
property for more information. 有关详细信息,请参阅http://api.jquery.com/jQuery.ajax/ ,特别是
dataType
属性。 Depending on what you eventually intend to return from that service (JSON, XML, etc.), you'll want to set that property accordingly in the object you pass to the $.ajax
call. 根据您最终打算从该服务返回的内容(JSON,XML等),您需要在传递给
$.ajax
调用的对象中相应地设置该属性。
The PHP script is returning the string 'dogcat'. PHP脚本返回字符串'dogcat'。 So when you're printing output[0], you'd obviously get the first character in the string.
所以当你打印输出[0]时,你显然会得到字符串中的第一个字符。
You need to separate your words echoed from the PHP script with some kind of separator, such "|", and have the javascript split the output by that. 您需要将从PHP脚本回显的单词与某种分隔符(例如“|”)分开,然后使用javascript将输出拆分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.