I made a simple example showing the problem: the form below submits to another page using jQuery .post().
Form
$('form').submit(function(){
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data) {
var ret = data;
var final_data = $(ret).find('#holder-1').html();
alert(final_data);
}
)
return false;
})
Action
<div id="holder-1">
<h1>Content 1</h1>
</div>
<div id="holder-2">
<h1>Content 2</h1>
</div>
<div id="holder-3">
<h1>Content 3</h1>
</div>
The log shows that the content of data looks fine. But once i try to find #holder-1 with .find(), it returns undefined.
This is almost the same as the last example in the jQuery api page: http://api.jquery.com/jQuery.post/
Here is the full (not) working example hosted in my website, with some console.log() along the code:
Form: http://www.peixelaranja.com.br/tmp/post.php
I tried nearly anything: passing the dataType as 4th parameter, using $.ajax() instead of .post(), using .filter() instead of .find(), different versions of jQuery... Nothing seems to work.
All the files are UTF-8.
Any ideas?
I know you mentioned that you used filter instead of find, however, that should work. jQuery is stripping out the html, head,body tags, etc. Once this is done, #holder-1 is now at the top level of the hierarchy.
This fiddle demonstrates that filter does work:
http://jsfiddle.net/68jEt/
var html = '<!doctype html><html dir="ltr" lang="pt-BR"><head> <meta charset="UTF-8"> <title>Return Test</title></head><body> <div id="holder-1"> <h1>Content 1</h1> </div> <div id="holder-2"> <h1>Content 2</h1> </div> <div id="holder-3"> <h1>Content 3</h1> </div></body></html>';
alert($(html).filter("#holder-1").html());
Related
I am trying to get the value of an element attribute from this site via importXML in Google Spreadsheet using XPath.
The attribute value i seek is content found in the <span> with itemprop="price".
<div class="left" style="margin-top: 10px;">
<meta itemprop="currency" content="RON">
<span class="pret" itemprop="price" content="698,31 RON">
<p class="pret">Pretul tau:</p>
698,31 RON
</span>
...
</div>
I can access <div class="left"> but i can't get to the <span> element.
Tried using:
//span[#class='pret']/#content i get #N/A;
//span[#itemprop='price']/#content i get #N/A;
//div[#class='left']/span[#class='pret' and #itemprop='price']/#content i get #N/A;
//div[#class='left']/span[1]/#content i get #N/A;
//div[#class='left']/span/text() to get the text node of <span> i get #N/A;
//div[#class='left']//span/text() i get the text node of a <span> lower in div.left.
To get the text node of <span> i have to use //div[#class='left']/text(). But i can't use that text node because the layout of the span changes if a product is on sale, so i need the attribute.
It's like the span i'm looking for does not exist, although it appears in the development view of Chrome and in the page source and all XPath work in the console using $x("").
I tried to generate the XPath directly form the development tool by right clicking and i get //*[#id='produs']/div[4]/div[4]/div[1]/span which does not work. I also tried to generate the XPath with Firefox and plugins for FF and Chrome to no avail. The XPath generated in these ways did not even work on sites i managed to scrape with "hand coded XPath".
Now, the strangest thing is that on this other site with apparently similar code structure the XPath //span[#itemprop='price']/#content works.
I struggled with this for 4 days now. I'm starting to think it's something to do with the auto-closing meta tag, but why doesn't this happen on the other site?
Perhaps the following formulas can help you:
=ImportXML("http://...","//div[#class='product-info-price']//div[#class='left']/text()")
Or
=INDEX(ImportXML("http://...","//div[#class='product-info-price']//div[#class='left']"), 1, 2)
UPDATE
It seems that not properly parse the entire document, it fails. A document extraction, something like:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<div class="product-info-price">
<div class="left" style="margin-top: 10px;">
<meta itemprop="currency" content="RON">
<span class="pret" itemprop="price" content="698,31 RON">
<p class="pret">Pretul tau:</p>
698,31 RON
</span>
<div class="resealed-info">
» Vezi 1 resigilat din aceasta categorie
</div>
<ul style="margin-left: auto;margin-right: auto;width: 200px;text-align: center;margin-top: 20px;">
<li style="color: #000000; font-size: 11px;">Rata de la <b>28,18 RON</b> prin BRD</li>
<li style="color: #5F5F5F;text-align: center;">Pretul include TVA</li>
<li style="color: #5F5F5F;">Cod produs: <span style="margin-left: 0;text-align: center;font-weight: bold;" itemprop="identifier" content="mol:GA-Z87X-UD3H">GA-Z87X-UD3H</span> </li>
</ul>
</div>
<div class="right" style="height: 103px;line-height: 103px;">
<form action="/?a=shopping&sa=addtocart" method="post" id="add_to_cart_form">
<input type="hidden" name="product-183641" value="on"/>
<img src="/templates/marketonline/images/pag-prod/buton_cumpara.jpg"/>
</form>
</div>
</div>
</html>
works with the following XPath query:
"//div[#class='product-info-price']//div[#class='left']//span[#itemprop='price']/#content"
UPDATE
It occurs to me that one option is that you can use Apps Script to create your own ImportXML function, something like:
/* CODE FOR DEMONSTRATION PURPOSES */
function MyImportXML(url) {
var found, html, content = '';
var response = UrlFetchApp.fetch(url);
if (response) {
html = response.getContentText();
if (html) content = html.match(/<span class="pret" itemprop="price" content="(.*)">/gi)[0].match(/content="(.*)"/i)[1];
}
return content;
}
Then you can use as follows:
=MyImportXML("http://...")
At this time, the referred web page in the first link doesn't include a span tag with itemprop="price", but the following XPath returns 639
//b[#itemprop='price']
Looks to me that the problem was that the meta tag was not XHTML compliant but now all the meta tags are properly closed.
Before:
<meta itemprop="currency" content="RON">
Now
<meta itemprop="priceCurrency" content="RON" />
For web pages that are not XHTML compliant, instead of IMPORTXML another solution should be used, like using IMPORTDATA and REGEXEXTRACT or Google Apps Script, the UrlFetch Service and the match JavasScript function, among other alternatives.
Try smth like this:
print 'content by key',tree.xpath('//*[#itemprop="price"]')[0].get('content')
or
nodes = tree.xpath('//div/meta/span')
for node in nodes:
print 'content =',node.get('content')
But i haven't tried that.
So to keep it simple, im trying to update my select list with a new list of items that i get from an ajax-call. The list has the items. I set the model to the new list and do a $scope.$apply(). This works great in firefox, but not in IE. What am I doing wrong? Is there some IE9-thing that I'm missing? (I've been looking for a few hours now and am ready to give up). Appreciate all the help I can get.
HTML:
<select
ng-model="SelectedParameter"
ng-options="Parameter.Name for Parameter in AllParameters">
</select>
JS:
$.getJSON("/Cont/GetList", {id: id},
function (result) {
var allParameters = result.Data.AllParameters;
$scope.AllParameters = allParameters;
$scope.$apply();
}
);
You'd be way better off doing this the "Angular way". No JQuery required! In fact, if you find yourself doing things the "JQuery way" you're probably doing it wrong. Mark Rajcok had a really good question (and answer) about this same thing on StackOverflow a while ago:
app.js
//declare your application module.
var app = angular.module('myApp', []);
//declare a controller
app.controller('MainCtrl', function($scope, $http) {
//function to update the list
$scope.updateList = function () {
$http.get('/Cont/GetList', function(data) {
$scope.allParameters = data;
});
};
//initial load
$scope.updateList();
});
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="angular.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="MainCtrl">
<button ng-click="updateList()">Update</button>
<ul>
<li ng-repeat="parameter in allParameters">{{parameter | json}}</li>
</ul>
<!-- EDIT: Because you requested a select.
or if you wanted to do a select list
assuming every object in your array had a "name" property
you wanted to display in the option text, you could do
something like the following:
(NOTE: ng-model is required for ng-options to work)
-->
<select ng-model="selectedValue" ng-options="p as p.name for p in allParameters"></select>
<!-- this is just to display the value you've selected -->
<p>Selected:</p>
<pre>{{selectedValue | json}}</pre>
</div>
</body>
</html>
EDIT: A common problem in IE
So first of all, if you're having a problem in IE, I'd recommend hitting F12 and seeing what errors you're getting in the console.
The most common issue I've seen that breaks things in IE relate to commands such as console.log() which don't exist in IE. If that's the case, you'll need to create a stub, like so:
//stub in console.log for IE.
console = console || {};
console.log = console.log || function () {};
I think it's an IE issue. Try setting display:none before you update, then remove the display setting after you update.
I believe it is this bug that is ultimately the problem. I've been pulling my hair out for a couple of days on something very similar, a select filtered off of another.
At the end of the day OPTIONS are being added dynamically and IE9 just chokes on it.
<div class="col-lg-2">
<div class="form-group">
<label>State</label>
<select data-ng-model="orderFilter.selectedState"
data-ng-options="s.StateAbbr for s in states"
data-placeholder="choose a state…"
class="form-control">
<option value=""></option>
</select>
</div>
</div>
<div class="col-lg-2">
<div class="form-group">
<label>County</label>
<select data-ng-model="orderFilter.selectedCounty"
data-ng-options="c.CountyName for c in filteredCounties | orderBy:'CountyName'"
data-ng-disabled="orderFilter.selectedState == null"
data-placeholder="Choose a county…"
class="form-control">
<option value=""></option>
</select>
</div>
</div>
Regards,
Stephen
Basically the template wont render to a ScrollView using kendo.render(template, response) but WILL work with content = template(response) - BUT this has no styling in view -- see comment below
How to make the template render with kendo stylign in view?
BTW response from api call is JSON:
{"event_id":"5","stamp":"2013-01-24 06:00:00","type":"Event Type","loc":"Location","status":"1"}
<!-- eventDetail view -------------------------------------------------------------------------------------------------->
<div data-role="view" id="view-eventDetail" data-show="getEventDetailData" data-title="eventDetail">
<header data-role="header">
<div data-role="navbar">
<span data-role="view-title"></span>
<a data-align="right" data-role="button" class="nav-button" href="#view-myEvents">Back</a>
</div>
</header>
<div id="eventDetail" data-role="page"></div>
</div>
<script id="eventDetail-template" type="text/x-kendo-template">
--><form id="addEventForm"><p>
<input name="event_type" id="event_type" data-min="true" type="text" value="#= type #" />
</p>
<p>
<input name="event_loc" id="event_loc" data-min="true" type="text" value="#= loc #" />
</p>
<p>
<input name="event_date_time" id="event_date_time" data-min="true" type="datetime" value="#= stamp#" />
</p>
<p>
Share this
<input data-role="switch" id="event_share" data-min="true" checked="checked" value="1"/></p>
<p>
<input type="button" id="eventCancelButton" style="width:30%" data-role="button" data-min="true" value="Cancel" />
<input type="submit" id="eventDoneButton" style="width:30%" data-role="button" data-min="true" value="Done" />
</p></form><!--
</script>
<script>
//eventDetail engine
function getEventDetailData(e) {
$.ajax({
url: 'http://localhost/mpt/website/api/event_details.php?',
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { userID: 2, eventID: e.view.params.id },
success: function(response) {
console.log(response);
var template = kendo.template($("#eventDetail-template").html()),
content = template(response);//works but no kendo css
//content = kendo.render(template, response);not working
$("#eventDetail")
.kendoMobileScrollView()
.data("kendoMobileScrollView")
.content("<!--" + content + "-->");
}
});
}</script>
The widget classes (like km-button) are not added until the widget is initialized.
The template() and render() functions just return the template as a string with the data replaced (replaces #=foo# with the value of the foo property) but does not init all the widgets. In fact, it coldn't initialize the widgets if it wanted to singe it just returns a text string, not DOM elements. The initialization of the widgets is usually done by the parent widget that is using the template.
render() is not working in your case because its 2nd argument is supposed to be an array. All it does is call the given template function once per item in the array and concatenate the results. If you instead did:
var content = kendo.render(template, [response]); // wrap response in an array
it would return the same text string as template(response). It just provides a way to apply the same template to many items at once.
Normally when you create a widget, in your case calling .kendoMobileScrollView() you would expect it to turn any HTML contents of that element into widgets too, but it looks like the ScrollView widget doesn't do this. I think its intent may have been to just display pages of static content, not other widgets.
There is a Kendo method that isn't listed in the docs, kendo.mobile.init(contents); that you might be able to use to turn your template string into widgets. When I tried it in a jsFiddle it threw some error for me, but you could try something like:
var content = template(response); // apply response to template
var contentElements = $(content); // turn the string into DOM elements
kendo.mobile.init(contentElements); // turn elements into widgets (this throws error for me)
$("#eventDetail").html(contentElements); // add contents to the desired element
$("#eventDetail").kendoMobileScrollView(); // create the scroll view
Also, what is with the end and begin comment bits hanging off the ends of the template? I don't see why those are needed. Might be better to remove them.
The ScrollView widget is supposed to take a series of <div> elements as its children. It then pages between them as you swipe left/right across the control. I don't see you adding a series of <div>s anywhere.
I have this view:
<script type="text/x-handlebars" data-template-name="articlesOne">
<div class="main">
<div id="articlesOne">
<h2 id="article-title">{{App.ArticlesOneController.article.title}}</h2>
<h3 id="article-lead">{{App.ArticlesOneController.article.lead}}</h3>
<div id="article-body">{{App.ArticlesOneController.article.body}}</div>
</div>
</div>
</script>
When I change the App.ArticlesOneController.article.title property to, say <p>Pragraph</p>, the browser displays the plain text, not parsed as HTML.
I would like to display that in HTML, due to building an editor on that div. How should I do that?
You should try triple brackets with {{{App.ArticlesOneController.article.title}}}. I think this link is useful for you: Show property which includes html tags
I'm trying to get started with Ajax on MVC
In my main view I have the following code:
#Ajax.ActionLink("Click here to get the data","LoadData",
new AjaxOptions
{
UpdateTargetId = "dataPanel",
InsertionMode = InsertionMode.InsertAfter,
HttpMethod="GET"
})
<div id="dataPanel">
</div>
I created the controller's action as below:
public PartialViewResult LatestReview()
{
var myData = GetMyData();
return PartialView("_PartialData", myData);
}
_PartialData is defined as below:
#model MyApp.Models.Data
<div>
#if (Model == null)
{
<p>There is no data yet</p>
}
else
{
<p>
#Model.Body
</p>
}
</div>
But when I click the link, my data (rendered in the _PartialData) is loaded fully in browser, replacing the source page (so not inside the dataPanel div)
When I look at original page source (before clicking the ajax link) It see the ajax actions define as below:
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="after" data-ajax-update="#dataPanel" href="/Home/LoadData">Click here to get the data</a>
<div id="dataPanel">
</div>
What am I doing wrong?
Thanks
I suspect that you forgot to include the jquery unobtrusive ajax script to your page:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
It is this script that makes sense of all Ajax.* helper in ASP.NET MVC 3. Without it they generate standard markup with HTML5 data-* attributes which are used by the script.