Javascript for循环发布表单

时间:2013-10-23 21:25:01

标签: javascript php forms loops submit

for循环遍历来自facebook api的数据(json)。 现在我想把fb数据放在我自己的数据库中(用于其他网站)

问题不在于读取数据,而是在提交中的某处 看起来我只能提交一次 我认为theForm [x]是问题。

代码是:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
  FB.init({
    appId      : ***, // App ID
    status     : true, // check login status
    cookie     : true, // enable cookies to allow the server to access the session
    xfbml      : true  // parse XFBML
  });



  // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
  // for any authentication related change, such as login, logout or session refresh. This means that
  // whenever someone who was previously logged out tries to log in again, the correct case below 
  // will be handled. 
  FB.Event.subscribe('auth.authResponseChange', function(response) {
    // Here we specify what we do with the response anytime this event occurs. 
    if (response.status === 'connected') {
      // The response object is returned with a status field that lets the app know the current
      // login status of the person. In this case, we're handling the situation where they 
      // have logged in to the app.
      testAPI();
    } else if (response.status === 'not_authorized') {
      // In this case, the person is logged into Facebook, but not into the app, so we call
      // FB.login() to prompt them to do so. 
      // In real-life usage, you wouldn't want to immediately prompt someone to login 
      // like this, for two reasons:
      // (1) JavaScript created popup windows are blocked by most browsers unless they 
      // result from direct interaction from people using the app (such as a mouse click)
      // (2) it is a bad experience to be continually prompted to login upon page load
      FB.login(function() {
   // handle the response

        }, {scope: 'friends_relationships,friends_relationship_details,friends_photos,friends_about_me,user_about_me,friends_hometown,friends_location'});

    } else {

      // In this case, the person is not logged into Facebook, so we call the login() 
      // function to prompt them to do so. Note that at this stage there is no indication
      // of whether they are logged into the app. If they aren't then they'll see the Login
      // dialog right after they log in to Facebook. 
      // The same caveats as above apply to the FB.login() call here.
      FB.login(function() {
   // handle the response
        }, {scope: 'friends_relationships,friends_relationship_details,friends_photos,friends_about_me,user_about_me,friends_hometown,friends_location'});

        }
  });
  };


 // Load the SDK asynchronously
  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/all.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));



  // Here we run a very simple test of the Graph API after login is successful. 
  // This testAPI() function is only called in those cases. 
  function testAPI() {
   var $tokenx =   $(FB.getAuthResponse()['accessToken']);
     printTable($tokenx.selector);
    };




    function printTable(token){

    FB.api('/me?fields=name,gender,friends.fields(relationship_status,name,gender,location,picture.width(200).height(200))', function(myList) {



        var theForm = [];
         for (var x = 0 ; x < myList.friends.data.length ; x++){
         console.log(myList.friends.data[x].id + myList.friends.data[x].name);
        // postPage(myList.friends.data[x].id, myList.friends.data[x].name);
         var newInput1, newInput2;
  // Start by creating a <form>
  theForm[x] = document.createElement('form');
  theForm[x].id = x;
  theForm[x].name = x;
  theForm[x].target = "hiddenFrame";
  theForm[x].action = "insert.php";
  theForm[x].method = 'post';
  // Next create the <input>s in the form and give them names and values
  newInput1 = document.createElement('input');
  newInput1.type = 'text';
  newInput1.name = 'id';
  newInput1.value = myList.friends.data[x].id;
  newInput2 = document.createElement('input');
  newInput2.type = 'text';
  newInput2.name = 'naam';
  newInput2.value = myList.friends.data[x].name;
  // Now put everything together...
  theForm[x].appendChild(newInput1);
  theForm[x].appendChild(newInput2);

  theForm[x].submit();
  //document.getElementById(theForm[x]).submit();

         }
         }
            }
            )};



/*          
 function postPage (id2,naam2) {
  var theForm, newInput1, newInput2;
  // Start by creating a <form>
  theForm = document.createElement('form');
  theForm.target = "hiddenFrame";
  theForm.action = "insert.php";
  theForm.method = 'post';
  // Next create the <input>s in the form and give them names and values
  newInput1 = document.createElement('input');
  newInput1.type = 'text';
  newInput1.name = 'id';
  newInput1.value = id2;
  newInput2 = document.createElement('input');
  newInput2.type = 'text';
  newInput2.name = 'naam';
  newInput2.value = naam2;
  // Now put everything together...
  theForm.appendChild(newInput1);
  theForm.appendChild(newInput2);

  theForm.submit();
alert(id2 + " - " + naam2);
};
*/

</script>
<iframe src="insert.php" name="hiddenFrame"></iframe>

<form method="post" action="insert.php" target="hiddenFrame">
naam<input type="text" name="naam"><br>
id<input type="text" name="id">
<input type="submit" name="submit">
</form>
</body>
</html>

insert.php看起来像(删除了数据库连接“host”,“user”,“pass”,“table”):

<?php
$db=mysql_connect("host","user","pass")or die(mysql_error());
mysql_select_db("table",$db);

$id = $_POST[id];
$naam = $_POST[naam];
$sql = "SELECT COUNT(*) AS count FROM USERS WHERE ID='$id'";
$result = mysql_query($sql);
$result = mysql_fetch_assoc($result);
$count = $result['count'];

echo $count;
echo " - ";
echo $id;


if($count > 0){
   //found

}else{
   $sql="INSERT INTO USERS(ID,NAME)VALUES('$id','$naam')";
    mysql_query($sql,$db);
}

mysql_close($db);
?>

很抱歉长代码,但我不认为部分是可能的 我再次认为theForm [x]是问题,但我找不到它。

感谢有人能指出我正确的方向。

聚苯乙烯。我知道我的代码很混乱:(

2 个答案:

答案 0 :(得分:2)

theForm[x].submit();

.submit()就像点击提交按钮一样。

那么你的脚本会发生什么:

  1. for 循环开始。 (x = 0)
  2. 创建表单[0]
  3. 创建所有输入字段并使用值
  4. 填充它们
  5. 提交表单(又称POST到insert.php )和“中断” for 循环。
  6. 取而代之的是用户jQuery的 $。发布。它应该是这样的:

    $.post('insert.php', {id: myList.friends.data[x].id, naam: myList.friends.data[x].name}, function(data){
        // handle response here if required
    });
    

    如果您遇到重复的帖子/值的问题,可能是因为$ .post请求是异步的。

    有关如何执行同步请求的信息,请查看此页面... 的 http://api.jquery.com/jQuery.ajax/

答案 1 :(得分:0)

我猜你在数据库中只记录了 myList 的第一个元素。那是因为一旦你调用了 .submit(),就会跳过你的for循环并刷新页面。我建议避免使用表单,只使用jQuery提出的简单的ajax请求(我看到你已经在使用它了) - &gt; http://api.jquery.com/jQuery.post/