2016-11-13 78 views
0

我正在從事一個學校項目,該項目涉及使用各種AP​​I/AJAX調用從多個在線零售商提取產品數據,然後使用PHP對這些數據進行排序(我使用一個AJAX調用爲每個零售商)。下面顯示了我正在處理的代碼片段。我不能找出一個臨時數組含有產物如何如何將二維數組從JavaScript傳遞到PHP

  1. 推屬性(「平均」,「價格」,「姓名」,「地址」和「圖像」),用於每一個產品到主陣列(陣列)然後

  2. 將這個主數組發送到PHP,以便我可以將它的值編入索引以便進行排序。

function get_results() { 
    $(document).ready(function() { 
    var master_array = []; 
    $.ajax({ 
     type: "GET", 
     url: "http//:www.source1.com", 
     dataType: "xml", 
     success: function(xml) { 
     $(xml).find('product').each(function() { 
      var Average = $(this).find('Average').text(); 
      var Price = $(this).find('Price').text(); 
      var Name = $(this).find('Name').text(); 
      var Url = $(this).find('Url').text(); 
      var Image = $(this).find('Image').text(); 
      master_array.push([Average, Price, Name, Url, Image]); 
     }); 
     } 
    }); 
    $.ajax({ 
     type: "GET", 
     url: "http//:www.source2.com", 
     dataType: "xml", 
     success: function(xml) { 
     $(xml).find('product').each(function() { 
      var Average = $(this).find('Average').text(); 
      var Price = $(this).find('Price').text(); 
      var Name = $(this).find('Name').text(); 
      var Url = $(this).find('Url').text(); 
      var Image = $(this).find('Image').text(); 
      master_array.push([Average, Price, Name, Url, Image]); 
     }); 
     } 
    }); 
    }); 
} 

回答

1

您應該看到jQuery的AJAX功能的示例代碼:http://api.jquery.com/jquery.ajax/。下面是一個例子代碼:

$.ajax({ 
    method: "POST", 
    url: "some.php", 
    data: { name: "John", location: "Boston" } 
}) 
.done(function(msg) { 
    alert("Data Saved: " + msg); 
}); 

你更新的功能,可以是這樣的:

function get_results() { 
    $(document).ready(function() { 
    var master_array = []; 
    $(xml).find('product').each(function() { 
     var Average = $(this).find('Average').text(); 
     var Price = $(this).find('Price').text(); 
     var Name = $(this).find('Name').text(); 
     var Url = $(this).find('Url').text(); 
     var Image = $(this).find('Image').text(); 
     master_array.push([Average, Price, Name, Url, Image]); 
    }); 
    $.ajax({ 
     type: "POST", 
     url: "http//:www.source1.com", 
     data: master_array, 
     success: function(response) { 
     alert('Data successfully posted'); 
     }, 
    fail: function(response) { 
     alert('Data could not be posted'); 
     } 
    }); 

    }); 
} 

在上面的代碼的成功和失敗都當服務器返回響應所調用的函數。如果響應正確發送,則調用成功功能。如果服務器上有錯誤,則調用失敗函數。