此代码返回$ .getJSON中的数据两次,除非我激活evnt.stopImmediatePropagation(); line,在这种情况下我的Android移动设备上没有返回任何数据:
$(document).on('click', '#LoginClick', function(evnt) {
// evnt.stopImmediatePropagation();
// Find other players
// Send a call to the backend for players
var lilength = $('li').length;
if (lilength == 0) {
$.getJSON('http://www.cjneeds.com/ECG/getPlayers.php', function(Users) {
// For each Player, add them to the list
$.each(Users, function(i,User) {
// Add each Player to the list
$('<li/>').text(User['userName']).appendTo("#playerList");
});
// Refresh the list
$("#playerList").listview('refresh');
});
}
});
这是html:
<div id="LoginPage" data-role="page">
<div data-role="header"><h1>Login to ECG</h1>
<a id="LoginClick" href="#LoginSubmit" title="Submit login details">Submit</a>
</div>
<div data-role="content">
<form>
<div>
<label for="UserName">User name</label>
<input id="UserName" title="Enter your User Name" tabindex="1" type="text" placeholder="User name" maxlength="10" autofocus>
</div>
.
.
.
</form>
</div>
<div data-role="footer"><h1>Educational card games</h1>
<a href="#" title="Retrieve your password">Lost PW</a>
</div>
</div>
<div id="LoginSubmit" data-role="page">
<div data-role="header"><h1>You're up against:</h1>
<a href="#DisplayHand" title="See your cards and the upturned card">Play</a>
</div>
<div data-role="content">
<ol id="playerList" data-role="listview">
<!-- The <li> elements of Players go here. -->
</ol>
</div>
<div data-role="footer"><h1>To see your cards click 'Play'</h1></div>
</div>
和服务器上的php:
<?php
class User {
public $userName;
public $password;
public $emailAddress;
public $ageLast;
}
// Make a list for Users
$Users = array();
// Make new User 1
$Users[0] = new User;
$Users[0]->userName = 'John';
$Users[0]->password = 'John';
$Users[0]->emailAddress = 'john@email.com';
$Users[0]->ageLast = '9';
// Make new User 2
$Users[1] = new User;
$Users[1]->userName = 'Jane';
$Users[1]->password = 'Jane';
$Users[1]->emailAddress = 'jane@email.com';
$Users[1]->ageLast = '8';
// Make new User 3
$Users[2] = new User;
$Users[2]->userName = 'Sally';
$Users[2]->password = 'Sally';
$Users[2]->emailAddress = 'sally@email.com';
$Users[2]->ageLast = '9';
// Pass to client
echo json_encode($Users);
?>
并返回此值(当evnt.stopImmediatePropagation();行被清除时):
这似乎表明$ .getJSON或$ .each以某种方式执行了两次?
我尝试设置fiddle,但无法使json部分正常工作。
答案 0 :(得分:0)
这是因为您正在处理click
上的$(document)
事件。请在链接本身处理它,以避免触发两次:$('#LoginClick').on('click', function() {...
。
即使这样,我建议停止事件传播,因为您正在使用链接的点击事件,该事件定义了不同的默认行为。